Skip to content

Commit aceadc9

Browse files
Kincaid Savoiepkittenis
authored andcommitted
Added function to copy files from remote host to local host in ssh_client.
1 parent 967b205 commit aceadc9

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

pssh/ssh_client.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,3 +378,48 @@ def copy_file(self, local_file, remote_file, recurse=False):
378378
raise error
379379
logger.info("Copied local file %s to remote destination %s:%s",
380380
local_file, self.host, remote_file)
381+
382+
def _copy_dir_to_local(self, remote_dir, local_dir):
383+
"""Copies the remote directory to the local host."""
384+
sftp = self._make_sftp()
385+
file_list = sftp.listdir(remote_dir)
386+
for file_name in file_list:
387+
remote_path = os.path.join(remote_dir, file_name)
388+
local_path = os.path.join(local_dir, file_name)
389+
self.copy_file_to_local(remote_path, local_path, recurse=True)
390+
391+
def copy_file_to_local(self, remote_file, local_file, recurse=False):
392+
"""Copy remote file to local host via SFTP/SCP
393+
394+
Copy is done natively using SFTP/SCP version 2 protocol, no scp command \
395+
is used or required.
396+
397+
:param remote_file: Remote filepath to copy the file from.
398+
:type remote_file: str
399+
:param local_file: Local filepath where the file will be copied.
400+
:type local_file: str
401+
:param recurse: Whether or not to recursively copy directories.
402+
:type recurse: bool
403+
"""
404+
sftp = self._make_sftp()
405+
try:
406+
sftp.listdir(remote_file)
407+
remote_dir_exists = True
408+
except IOError or OSError:
409+
remote_dir_exists = False
410+
if remote_dir_exists and recurse:
411+
return self._copy_dir_to_local(remote_file, local_file)
412+
destination = [_dir for _dir in local_file.split(os.path.sep)
413+
if _dir][:-1][0]
414+
if local_file.startswith(os.path.sep):
415+
destination = os.path.sep + destination
416+
if not os.path.exists(destination):
417+
os.mkdir(destination)
418+
try:
419+
sftp.get(remote_file, local_file)
420+
except Exception, error:
421+
logger.error("Error occured copying file %s from remote destination %s:%s - %s",
422+
local_file, self.host, remote_file, error)
423+
else:
424+
logger.info("Copied local file %s from remote destination %s:%s",
425+
local_file, self.host, remote_file)

0 commit comments

Comments
 (0)