[Python] Using SFTP and RSA keys to remotely copy files

Source: Internet
Author: User

If the two servers use the RSA key-free password-based login method, you can first find the corresponding directory of the RSA key (such as find/-name id_rsa or locate id_rsa ),

The following code uses the paramiko module in Python to implement the SCP function:

Def scp_by_key (host_ip, host_port, remote_path, local_path, username, pkey_path): Try: Key = paramiko. rsakey. from_private_key_file (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 SFTP. get (SRC, des) T. close () failed t exception as E: Print E

We can use this method as follows:

Scp_by_key ('2017. 168.0.33 ', 22,'/XX/XXX/a.txt ', 'xx/XXX/B .txt', 'xiaomo', '/home/xiaomo /. SSH/id_rsa ')

Is it easy to use? However, the premise is to have an RSA key... if you need a password, you only need to replace the pkey parameter with the password to pass in:

T = paramiko. Transport (host_ip, host_port) T. Connect (username = username, password = 'xxx ')

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.