SoFunction
Updated on 2024-11-20

Python based on sftp and rsa key to realize the remote copy file method

This article example describes Python based on sftp and rsa secret key to realize the remote copy file method. Shared for your reference, as follows:

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

The scp function can then be implemented in the paramiko module in Python like this.

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

We can use the method like this:

Copy Code The code is as follows.
scp_by_key('192.168.0.33', 22, '/xx/xxx/', 'xx/xxx/', 'xiaomo', '/home/xiaomo/.ssh/id_rsa')

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

t = ((host_ip, host_port))
(username=username, password='xxx')

Readers interested in more Python related content can check out this site's topic: theSummary of Python file and directory manipulation techniques》、《Summary of Python text file manipulation techniques》、《Summary of Python URL manipulation techniques》、《Summary of Python image manipulation techniques》、《Python Data Structures and Algorithms Tutorial》、《Python Socket Programming Tips Summary》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials

I hope that what I have said in this article will help you in Python programming.