python中的paramiko模塊

python的paramiko模塊html

此文章轉載於https://www.cnblogs.com/breezey/p/6663546.html,若有侵權,請聯繫。python

 
    paramiko是用python語言寫的一個模塊,遵循SSH2協議,支持以加密和認證的方式,進行遠程服務器的鏈接。paramiko支持Linux, Solaris, BSD, MacOS X, Windows等平臺經過SSH從一個平臺鏈接到另一個平臺。利用該模塊,能夠方便的進行ssh鏈接和sftp協議進行sftp文件傳輸。
 
paramiko經常使用的類與方法:
 
一、SSHClient類
SHClient類是SSH服務會話的高級表示,封裝了傳輸、通道以及SFTPClient的校驗、創建方法,一般用於執行命令。
 
1)connect方法
connect(self,hostname,port=22,username=None,password=None,pkey=None,key_filename=None,timeout=None,allow_agent=True,look_for_keys=True,compress=False)
參數說明:
hostname:鏈接目標的主機地址
port:鏈接目錄的端口,默認爲22
username:用戶名
password:密碼
pkey:私鑰方式用戶驗證
key_filename:私鑰文件名
timeout:鏈接超時時間
allow_agent:是否容許使用ssh代理
look_for_keys:是否容許搜索私鑰文件
compress:打開時是否壓縮
 
2)exec_command方法
exec_command(self,command,bufsize=-1)
參數說明:
command:執行的的指令
bufsize:文件緩衝區大小,-1不限制
 
3)load_system_host_keys方法
load_system_host_keys(self,filename=None)
參數說明:
filename:指定遠程主機的公鑰文件,默認爲.ssh目錄下的known_hosts文件
 
4)set_missing_host_key_policy方法
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
參數說明:
AutoAddPolicy:自動添加主機名及密鑰到本地並保存,不依賴load_system_host_keys()配置,即若是known_hosts裏沒有遠程主機的公鑰時,默認鏈接會提示yes/no,自動yes
RejectPolicy:自動拒絕未知主機名和密鑰,依賴load_system_host_keys()
WarnningPlicy:功能與AutoAddPolicy相同,可是未知主機會提示yes/no
 
二、SFTPClient類
根據SSH傳輸協議的sftp會話,實現遠程文件上傳、下載等操做。
 
1)from_transport方法
 
classmethod from_transport(cls,t)
參數說明:
t:一個已經過驗證的傳輸對象
 
示例:
>>> import paramiko >>> a = paramiko.Transport((「127.0.0.1″,2222)) >>> a.connect(username=」root」, password=’123456′) >>> sftp = paramiko.SFTPClient.from_transport(a)
 
2)put方法
 
put(self,localpath,remotepath,callback=None,confirm=True)
參數說明:
localpath:上傳源文件的本地路徑
remotepath:目標路徑
callback:獲取接收與總傳輸字節數
confirm:上傳完畢後是否調用stat()方法,以便確認文件大小
 
示例:
>>> localpath=’ftp-test.log’
>>> remotepath=’/data/ftp-test.log’ >>> sftp.put(localpath,remotepath)

 

 
3)get方法
 
get(self, remotepath, localpath, callback=None)
參數說明:
remotepath:須要下載的遠程文件
localpath:本地存儲路徑
callback:同put方法
 
4)其餘方法
 
mkdir:用於建立目錄
remove:刪除目錄
rename:重命名
stat:獲取文件信息
listdir:獲取目錄列表
 
代碼示例
Paramiko ssh客戶端:
複製代碼
#!/usr/bin/python import paramiko import os,sys ssh_host = sys.argv[1] ssh_port = 22 user = 'root' password = 'xxxxxx' cmd = sys.argv[2] paramiko.util.log_to_file('/tmp/test') #使用paramiko記錄日誌 s = paramiko.SSHClient() #綁定一個實例 s.load_system_host_keys() #加載known_hosts文件 s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #遠程鏈接若是提示yes/no時,默認爲yes s.connect(ssh_host,ssh_port,user,password,timeout=5) #鏈接遠程主機 stdin,stdout,stderr = s.exec_command(cmd) #執行指令,並將命令自己及命令的執行結果賦值到標準辦入、標準輸出或者標準錯誤 cmd_result = stdout.read(),stderr.read() #取得執行的輸出 for line in cmd_result:   print line s.close()
複製代碼
 
使用ssh密鑰鏈接:
pkey_file = '/home/breeze/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(pkey_file) s.connect(host,port,username,pkey=key,timeout=5) stdin,stdout,stderr = s.exec_command(cmd)
 
Paramiko SFTP傳送文件:
複製代碼
#!/usr/bin/python import os,sys import paramiko host = sys.argv[1] rfilename = sys.argv[2] lfilename = os.path.basename(rfilename) user = 'root' password = 'xxxx' paramiko.util.log_to_file('/tmp/test') t = paramiko.Transport((host,22)) t.connect(username=user,password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(rfilename,lfilename) #sftp.put('paramiko1.py','/tmp/paramiko1.py') t.close()
複製代碼

 

 
使用interactive模塊實現SSH交互:
interactive.py模塊內容以下:
複製代碼
#!/usr/bin/python import socket import sys # windows does not have termios... try: import termios import tty has_termios = True except ImportError: has_termios = False def interactive_shell(chan): if has_termios: posix_shell(chan) else: windows_shell(chan) def posix_shell(chan): import select oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) chan.settimeout(0.0) while True: r, w, e = select.select([chan, sys.stdin], [], []) if chan in r: try: x = chan.recv(1024) if len(x) == 0: print '\r\n*** EOF\r\n', break sys.stdout.write(x) sys.stdout.flush() except socket.timeout: pass if sys.stdin in r: x = sys.stdin.read(1) if len(x) == 0: break chan.send(x) finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty) # thanks to Mike Looijmans for this code def windows_shell(chan): import threading sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n") def writeall(sock): while True: data = sock.recv(256) if not data: sys.stdout.write('\r\n*** EOF ***\r\n\r\n') sys.stdout.flush() break sys.stdout.write(data) sys.stdout.flush() writer = threading.Thread(target=writeall, args=(chan,)) writer.start() try: while True: d = sys.stdin.read(1) if not d: break chan.send(d) except EOFError: # user hit ^Z or F6 pass
複製代碼
 
inter_ssh.py交互腳本以下:
複製代碼
#!/usr/bin/python #_*_coding:utf8_*_ import paramiko import interactive #記錄日誌 paramiko.util.log_to_file('/tmp/test') #創建ssh鏈接 ssh=paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('192.168.128.82',port=22,username='root',password='cheyian') #創建交互式shell鏈接 channel=ssh.invoke_shell() #創建交互式管道 interactive.interactive_shell(channel) #關閉鏈接 channel.close() ssh.close()
相關文章
相關標籤/搜索