Copy (scp) a file (or folder) on a remote server with Python

Using Python's paramiko package, you can easily and quickly write a script to copy files from a remote server to this machine.

Core steps:

1. Use the connection information to initialize the SSH client ;

2. Use SSH client to initialize SCP client ;

3. Use the get method of the SCP client to obtain the files on the remote server.

  1. import them
  2. import paramiko
  3. import unicodedata
  4. from scp import SCPClient
  5. client = paramiko.SSHClient()
  6. client.load_system_host_keys()
  7. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  8. client.connect( 'server IP address' , server SSH port, 'server login account' , 'server login password' )
  9. scp = SCPClient(client.get_transport())
  10. # Get all the folders on the server
  11. stdin, stdout, stderr = client.exec_command(
  12. 'find file path on server -type l'
  13. )
  14. # Traverse all the folders on the remote server, if it does not exist on the local server, scp it over
  15. for line in stdout:
  16. dir = line.strip("\n")
  17. # Extract the file name
  18. file_name = dir .split( '/' )[number]
  19. if os.path.exists( 'The local path to be copied into' + file_name):
  20. print('sub dir %s already exists. skip it' % file_name)
  21. else:
  22. print('start to copy %s...' % file_name)
  23. scp.get(os.path.join( dir ), 'the local path to be copied into' , recursive= True )
  24. scp.close()
  25. client.close()


Related: Copy (scp) a file (or folder) on a remote server with Python