Python implements a remote copy method based on sftp and rsa keys

  • 2020-05-12 02:47:39
  • OfStack

This article illustrates an example of how Python can copy files remotely based on sftp and rsa keys. I will share it with you for your reference as follows:

If a password-free login with RSA secret keys is used between two servers, the corresponding directory of rsa secret keys can be found first (e.g. find / -name id_rsa or locate id_rsa).

Then, scp function can be realized by paramiko module in Python:

def scp_by_key(host_ip, host_port, remote_path, local_path, username, pkey_path):
    t = paramiko.Transport((host_ip, host_port))
    t.connect(username=username, pkey=key)
    sftp = paramiko.SFTPClient.from_transport(t)
    src = remote_path
    des = local_path
  except Exception as e:
    print e

We can use this method as follows:

scp_by_key('', 22, '/xx/xxx/a.txt', 'xx/xxx/b.txt', 'xiaomo', '/home/xiaomo/.ssh/id_rsa')

Isn't it fun to use? But only if you have an rsa key... If you need a password, just pass in the pkey parameter instead of password:

t = paramiko.Transport((host_ip, host_port))
t.connect(username=username, password='xxx')

More about Python related topics: interested readers to view this site "Python file and directory skills summary", "Python skills summary text file", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article is helpful to you Python programming.

Related articles: