Python + Paramiko实现sftp文件上传下载

导言:春节回家倒计时3天,昨晚打电话给爸妈,家里亲人很多都回去了,连今天楼下的包子店都因为春节暂停营业了,顿时好像回家,上班都没心情了,迫不及待,回家归回家,工作归工作,还是得好好工作的,最近在测试服务器那块,看了下Paramiko模块,一直都是用FileZilla工具,想了想,持续集成,更新代码可以用Parmmiko完成,还是不错的

Paramiko是用python语言写的一个模块,远程连接到Linux服务器,查看上面的日志状态,批量配置远程服务器,文件上传,文件下载等

初始化一些参数:

host = "120.24.239.214"
port = 22
timeout = 30
user = "root"
password = "******"

Paramiko远程执行linux命令:

# -*- 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")

Paramiko上传文件:

# -*- 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")

Paramiko下载文件:

# -*- 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")

Python还有个默认的ftplib模块定义了FTP类,其中函数有限,可用来实现简单的ftp客户端,用于上传或下载文件

ftp相关命令操作:

ftp.cwd(pathname)   #设置FTP当前操作的路径
ftp.dir()   #显示目录下文件信息
ftp.nlst()  #获取目录下的文件
ftp.mkd(pathname)   #新建远程目录
ftp.pwd()    #返回当前所在位置
ftp.rmd(dirname)    #删除远程目录
ftp.delete(filename)    #删除远程文件
ftp.rename(fromname, toname)    #将fromname修改名称为toname。
ftp.storbinaly("STOR filename.txt",file_handel,bufsize)     #上传目标文件
ftp.retrbinary("RETR filename.txt",file_handel,bufsize)     #下载FTP文件

一些小例子:

# -*- 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")
        # 以ASCII模式下载文件
        # f.retrlines("RETE patch8.gz", writeline)
        # 以二进制模式下载文件
        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

总结:

Parmmiko很好的完成sftp文件传输操作,可以用在SVN管理代码项目中进行持续集成开发或者测试

本人利用Bootstrap + EasyUI + Django开发网站:http://www.xuyangting.com/ 欢迎来访

阳台测试: 239547991(群号)

本人博客:http://xuyangting.sinaapp.com/

你可能感兴趣的:(python,paramiko)