Python + Paramiko implements sftp file upload and download

Introduction: The countdown to going home for the Spring Festival is 3 days. I called my parents last night. Many relatives at home have gone back. Even today, the steamed bun shop downstairs is closed for the Spring Festival. , go home, go home, work is work, still have to work hard, recently in the test server, I looked at the Paramiko module, I have always used the FileZilla tool, after thinking about it, continuous integration, and updating the code can be done with Parmmiko ,not bad

Paramiko is a module written in python language, which can connect to Linux server remotely, view the log status above, configure remote server in batches, upload files, download files, etc.

Initialize some parameters:

host = "120.24.239.214"
port = 22
timeout = 30
user = "root"
password = "******"
  • 1
  • 2
  • 3
  • 4
  • 5

Paramiko executes linux commands remotely:

# -*- coding:utf-8 -*-
import paramiko

def sftp_exec_command(command):
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(host, 22, user, password)
        std_in, std_out, std_err = ssh_client.exec_command(command)
        for line in std_out:
            print line.strip("\n")
        ssh_client.close()
    except Exception, e:
        print e

if __name__ == '__main__':
    sftp_exec_command("ls -l")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Paramiko upload file:

# -*- coding:utf-8 -*-
import paramiko

def sftp_upload_file(server_path, local_path):
    try:
        t = paramiko.Transport((host, 22))
        t.connect(username=user, password=password)
        sftp = paramiko.SFTPClient.from_transport(t)
        sftp.put(local_path, server_path)
        t.close()
    except Exception, e:
        print e

if __name__ == '__main__':
    sftp_upload_file("/root/bug.txt", "D:/bug.txt")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Paramiko download file:

# -*- coding:utf-8 -*-
import paramiko

def sftp_down_file(server_path, local_path):
    try:
        t = paramiko.Transport((host, 22))
        t.connect(username=user, password=password)
        sftp = paramiko.SFTPClient.from_transport(t)
        sftp.get(server_path, local_path)
        t.close()
    except Exception, e:
        print e

if __name__ == '__main__':
    sftp_down_file("/root/test.txt", "D:/text.txt")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Python also has a default ftplib module that defines the FTP class, which has limited functions and can be used to implement a simple ftp client for uploading or downloading files.

FTP related command operations:

ftp .cwd(pathname) #Set    the path of the current FTP operation 
ftp .dir()    #Display   the file information in the directory 
ftp .nlst() #Get the files in the directory 
ftp .mkd(pathname) #Create    a new remote directory 
ftp .pwd()     #Return to the current location 
ftp.rmd (dirname) #Delete     the remote directory 
ftp.delete (filename)     #Delete the remote file ftp.rename ( fromname , toname )     #Change the name fromname to toname. ftp .storbinaly( "STOR filename.txt" ,file_handel,bufsize)      #Upload target file ftp .retrbinary( "RETR filename.txt" ,file_handel,bufsize)     


#Download FTP file
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Some small examples:

# -*- coding:utf-8 -*-
from ftplib import FTP, all_errors
import paramiko
import sys, os
import getpass

def ftp_main():
    try:
        f = FTP("ftp.ibiblio.org")
        print f.getwelcome()
        f.login()
        print f.pwd()
        f.quit()
    except Exception, e:
        print all_errors, e


def ftp_down_file():
    try:
        f = FTP("ftp.kernel.org")
        f.login()
        f.cwd("/pub/linux/kernel/v1.0")
        fd = open( "patch8.gz" , "wb" )
         # Download the file in ASCII mode 
        # f.retrlines("RETE patch8.gz", writeline) 
        # Download the file in binary mode 
        f.retrbinary( "RETE patch8.gz" , fd.write)
        fd.close()
        f.quit()
    except Exception, e:
        print all_errors, e


def ftp_up_file():
    try:
        host2, username, local_path, server_path = sys.argv[1:]
        password2 = getpass.getpass("Enter passworf for %s on %s:" % (username, host2))
        f = FTP(host2)
        f.login(user=username, passwd=password2)
        f.cwd(server_path)
        fd = open(local_path, "rb")
        f.storbinary("STOR %s" % os.path.basename(local_path), fd)
        fd.close()
        f.quit()
    except Exception, e:
        print all_errors, e
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

Summarize:

Parmmiko completes the sftp file transfer operation very well, and can be used for continuous integration development or testing in SVN management code projects

I use Bootstrap + EasyUI + Django to develop a website: http://www.xuyangting.com/ Welcome to visit

Balcony test: 239547991 (group number)

My blog: http://xuyangting.sinaapp.com/

Related: Python + Paramiko implements sftp file upload and download