Using Paramiko to implement SFTP

Source: Internet
Author: User
Tags file transfer protocol

SFTP is an SSH-based file Transfer protocol that is the most common way to transfer files to Linux on Windows (for example, securefx,xftp).

Under Python, Paramiko implements SFTP, allowing you to easily implement file transfer functionality in your code.

Official website is here: http://www.lag.net/paramiko/

You can use Easy_install Paramiko to install.

The following is a sample code that uses Paramiko to transfer files

01 importparamiko
02
03 username ="***"
04 password ="***"
05
06 hostname ="127.0.0.1"
07 port =22
08
09 try:
10     =paramiko.Transport((hostname, port))
11     t.connect(username=username, password=password)
12
13     sftp =paramiko.SFTPClient.from_transport(t)
14
15     sftp.put("/home/***/py_test/from/1.txt","/home/***/py_test/to/1.txt")
16     sftp.get("/home/***/py_test/to/2.txt","/home/***/py_test/from/2.txt")
17     t.close();
18 exceptException, e:
19     importtraceback
20     traceback.print_exc()
21     try:
22         t.close()
23     except:
24         pass

An sftp put means that a local file is transferred to a remote machine, and a get indicates that the remote file is passed to the local machine. Put and get need to explicitly write out the file name, unlike the SCP that can be omitted.

It is important to note that the put and get functions of SFTP only support a single file, if you need to transfer the entire directory, you need to manually use Sftp.mkdir to create a directory, and then traverse the entire folder, and use the put or get function for each file.

Using Paramiko to implement SFTP

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.