python is based on paramiko to upload files to the server code implementation

  • 2021-07-10 20:25:09
  • OfStack

python uses the paramiko module to upload local files to the server through installation


import paramiko
import datetime
import os

hostname = ' Server ip'
username = 'root'
password = ' Server password '
port = 22# Configuration information can be written to a configuration file 
#loacl_file Is the local file path to upload 
#remote_path Is the path to upload to the specified file on the server 
def upload(local_file, remote_path):
  try:
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    print(' Start uploading files %s ' % datetime.datetime.now())

    try:
      sftp.put(local_file, remote_path)
    except Exception as e:
      sftp.mkdir(os.path.split(remote_path)[0])
      sftp.put(local_file, remote_path)
      print(" From local:  %s  Upload to:  %s" % (local_file, remote_path))
    print(' File uploaded successfully  %s ' % datetime.datetime.now())
    t.close()
  except Exception as e:
    print(repr(e))


if __name__ == '__main__':
  local_file = r'/home/shl/dataETL/timings/words/word_pos.csv'
  remote_path = os.path.join('/home/',"word_pos.csv")
  upload(local_file, remote_path)

Related articles: