Python + Paramiko实现sftp文件上传下载
最近在測試服務器那塊,看了下Paramiko模塊,一直都是用FileZilla工具,想了想,持續集成,更新代碼可以用Parmmiko完成,還是不錯的
Paramiko是用python語言寫的一個模塊,遠程連接到Linux服務器,查看上面的日志狀態,批量配置遠程服務器,文件上傳,文件下載等
初始化一些參數:
host = "120.24.239.214" port = 22 timeout = 30 user = "root" password = "******"- 1
- 2
- 3
- 4
- 5
Paramiko遠程執行linux命令:
# -*- coding:utf-8 -*- import paramikodef 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 eif __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上傳文件:
# -*- coding:utf-8 -*- import paramikodef 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 eif __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下載文件:
# -*- coding:utf-8 -*- import paramikodef 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 eif __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還有個默認的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文件- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
一些小例子:
# -*- coding:utf-8 -*- from ftplib import FTP, all_errors import paramiko import sys, os import getpassdef ftp_main():try:f = FTP("ftp.ibiblio.org")print f.getwelcome()f.login()print f.pwd()f.quit()except Exception, e:print all_errors, edef 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, edef 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
總結:
Parmmiko很好的完成sftp文件傳輸操作,可以用在SVN管理代碼項目中進行持續集成開發或者測試
原文鏈接:http://blog.csdn.net/Temanm/article/details/50607741
這里還有一篇講得更詳細的,這在這里一并發過來,有助于加深理解。
paramiko模塊提供了ssh及sft進行遠程登錄服務器執行命令和上傳下載文件的功能。這是一個第三方的軟件包,使用之前需要安裝。
1 基于用戶名和密碼的 sshclient 方式登錄
# 建立一個sshclient對象 ssh = paramiko.SSHClient() # 允許將信任的主機自動加入到host_allow 列表,此方法必須放在connect方法的前面 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 調用connect方法連接服務器 ssh.connect(hostname='192.168.2.129', port=22, username='super', password='super') # 執行命令 stdin, stdout, stderr = ssh.exec_command('df -hl') # 結果放到stdout中,如果有錯誤將放到stderr中 print(stdout.read().decode()) # 關閉連接 ssh.close()- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
2 基于用戶名和密碼的 transport 方式登錄?
方法1是傳統的連接服務器、執行命令、關閉的一個操作,有時候需要登錄上服務器執行多個操作,比如執行命令、上傳/下載文件,方法1則無法實現,可以通過如下方式來操作
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
3 基于公鑰密鑰的 SSHClient 方式登錄
# 指定本地的RSA私鑰文件,如果建立密鑰對時設置的有密碼,password為設定的密碼,如無不用指定password參數 pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345') # 建立連接 ssh = paramiko.SSHClient() ssh.connect(hostname='192.168.2.129',port=22,username='super',pkey=pkey) # 執行命令 stdin, stdout, stderr = ssh.exec_command('df -hl') # 結果放到stdout中,如果有錯誤將放到stderr中 print(stdout.read().decode()) # 關閉連接 ssh.close()- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
4 基于密鑰的 Transport 方式登錄
# 指定本地的RSA私鑰文件,如果建立密鑰對時設置的有密碼,password為設定的密碼,如無不用指定password參數 pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345') # 建立連接 trans = paramiko.Transport(('192.168.2.129', 22)) trans.connect(username='super', pkey=pkey)# 將sshclient的對象的transport指定為以上的trans ssh = paramiko.SSHClient() ssh._transport = trans# 執行命令,和傳統方法一樣 stdin, stdout, stderr = ssh.exec_command('df -hl') print(stdout.read().decode())# 關閉連接 trans.close()- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
##### 傳文件 SFTP ###########
# 實例化一個trans對象# 實例化一個transport對象 trans = paramiko.Transport(('192.168.2.129', 22)) # 建立連接 trans.connect(username='super', password='super')# 實例化一個 sftp對象,指定連接的通道 sftp = paramiko.SFTPClient.from_transport(trans) # 發送文件 sftp.put(localpath='/tmp/11.txt', remotepath='/tmp/22.txt') # 下載文件 # sftp.get(remotepath, localpath) trans.close()- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
5 實現輸入命令立馬返回結果的功能?
以上操作都是基本的連接,如果我們想實現一個類似xshell工具的功能,登錄以后可以輸入命令回車后就返回結果:
- 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
- 47
- 48
- 49
- 50
- 51
- 52
- 53
6 支持tab自動補全
import paramiko import os import select import sys import tty import termios''' 實現一個xshell登錄系統的效果,登錄到系統就不斷輸入命令同時返回結果 支持自動補全,直接調用服務器終端''' # 建立一個socket trans = paramiko.Transport(('192.168.2.129', 22)) # 啟動一個客戶端 trans.start_client()# 如果使用rsa密鑰登錄的話 ''' default_key_file = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa') prikey = paramiko.RSAKey.from_private_key_file(default_key_file) trans.auth_publickey(username='super', key=prikey) ''' # 如果使用用戶名和密碼登錄 trans.auth_password(username='super', password='super') # 打開一個通道 channel = trans.open_session() # 獲取終端 channel.get_pty() # 激活終端,這樣就可以登錄到終端了,就和我們用類似于xshell登錄系統一樣 channel.invoke_shell()# 獲取原操作終端屬性 oldtty = termios.tcgetattr(sys.stdin) try:# 將現在的操作終端屬性設置為服務器上的原生終端屬性,可以支持tab了tty.setraw(sys.stdin)channel.settimeout(0)while True:readlist, writelist, errlist = select.select([channel, sys.stdin,], [], [])# 如果是用戶輸入命令了,sys.stdin發生變化if sys.stdin in readlist:# 獲取輸入的內容,輸入一個字符發送1個字符input_cmd = sys.stdin.read(1)# 將命令發送給服務器channel.sendall(input_cmd)# 服務器返回了結果,channel通道接受到結果,發生變化 select感知到if channel in readlist:# 獲取結果result = channel.recv(1024)# 斷開連接后退出if len(result) == 0:print("\r\n**** EOF **** \r\n")break# 輸出到屏幕sys.stdout.write(result.decode())sys.stdout.flush() finally:# 執行完后將現在的終端屬性恢復為原操作終端屬性termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)# 關閉通道 channel.close() # 關閉鏈接 trans.close() 原文鏈接:http://blog.csdn.net/songfreeman/article/details/50920767
其實,看這些中文版教程,如果能解決你的問題也確實是比較方便、快捷。然而,一旦遇到問題,出現各種異常的時候,看這些中文教程也就不知道如何去著手解決了,所以還是要養成一開始先搜素互聯網,看有哪些方式(python的哪些模塊,哪些方法)能解決類似的問題,然后查閱具體的官方API,這樣具體的方法、參數、使用方式都一目了然,而且記憶會更加深刻,解決問題后也更有成就感。所以,還是比較提倡去官方API查閱具體的使用方式的,遇到問題不能解決的時候,也不放回過頭來,重新翻看官方API,相信在這里一定會發現問題的端倪,從而解決掉問題的。
總結
以上是生活随笔為你收集整理的Python + Paramiko实现sftp文件上传下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java实现计时器
- 下一篇: python tk模块 小作业