SoFunction
Updated on 2024-11-12

Example of python paramiko uploading a directory to a remote using sftp

Most of the internet is uploading files, so I personally refer to some blogs on the internet and wrote a small program to upload a directory on windows to a remote linux.

Here's the code:

class ExportPrepare(object):
 def __init__(self):
 pass

 def sftp_con(self):
  t = ((, ))
  (username=, password=)
  return t

 # Find all the directories and files you want to upload.
 def __get_all_files_in_local_dir(self, local_dir):
  all_files = list()

  if (local_dir):
   files = (local_dir)
   for x in files:
    filename = (local_dir, x)
    print "filename:" + filename
    # isdir
    if (filename):
     all_files.extend(self.__get_all_files_in_local_dir(filename))
    else:
     all_files.append(filename)
  else:
   print '{}does not exist'.format(local_dir)
  return all_files

 # Copy a local file (localpath) to the SFTP server as remotepath
 def sftp_put_dir(self):
  try:
 # Upload the local test directory to the remote root/usr/ below
 local_dir = "c:/test"
 remote_dir = "/root/usr/test"
 
   t = self.sftp_con()
   sftp = .from_transport(t)
   # sshclient
   ssh = ()
   ssh.load_system_host_keys()
   ssh.set_missing_host_key_policy(())
   (, port=, username=, password=, compress=True)
   ssh.exec_command('rm -rf ' + remote_dir)
   if remote_dir[-1] == '/':
    remote_dir = remote_dir[0:-1]
   all_files = self.__get_all_files_in_local_dir(local_dir)
   for x in all_files:
    filename = (x)[-1]
    remote_file = (x)[0].replace(local_dir, remote_dir)
    path = remote_file.replace('\\', '/')
 # Create a directory sftp mkdir also works, but can't create multi-level directories so use ssh instead.
    tdin, stdout, stderr = ssh.exec_command('mkdir -p ' + path)
    print ()
    remote_filename = path + '/' + filename
    print u'Put files...' + filename
    (x, remote_filename)
   ()
  except Exception, e:
   print e
 
 
if __name__=='__main__':
 export_prepare = ExportPrepare()
 export_prepare.sftp_put_dir()

Rather hurried, shortcomings can be pointed out to improve together.

The above example of python paramiko using sftp to upload a directory to a remote is all that I have shared with you.