您好,登錄后才能下訂單哦!
本文研究的主要是Python Paramiko模塊的使用的實(shí)例,具體如下。
Windows下有很多非常好的SSH客戶端,比如Putty。在python的世界里,你可以使用原始套接字和一些加密函數(shù)創(chuàng)建自己的SSH客戶端或服務(wù)端,但如果有現(xiàn)成的模塊,為什么還要自己實(shí)現(xiàn)呢。使用Paramiko庫中的PyCrypto能夠讓你輕松使用SSH2協(xié)議。
Paramiko的安裝方法網(wǎng)上有很多這樣的帖子,這里就不描述了。這里主要講如何使用它。Paramiko實(shí)現(xiàn)SSH2不外乎從兩個角度實(shí)現(xiàn):SSH客戶端與服務(wù)端。
首先讓我們理清以下幾個名詞:
具體請參考Paramiko的庫文檔:http://docs.paramiko.org/en/2.0/index.html
下面給出幾個常用的使用案例:
這個方案直接使用SSHClient對象的exec_command()在服務(wù)端執(zhí)行命令,下面是具體代碼:
#實(shí)例化SSHClient client = paramiko.SSHClient() #自動添加策略,保存服務(wù)器的主機(jī)名和密鑰信息 client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #連接SSH服務(wù)端,以用戶名和密碼進(jìn)行認(rèn)證 client.connect(ip,username=user,password=passwd) #打開一個Channel并執(zhí)行命令 stdin,stdout,stderr = client.exec_command(command) #打印執(zhí)行結(jié)果 print stdout.readlines() #關(guān)閉SSHClient client.close()
這個方案是將SSHClient建立連接的對象得到一個Transport對象,以Transport對象的exec_command()在服務(wù)端執(zhí)行命令,下面是具體代碼:
#實(shí)例化SSHClient client = paramiko.SSHClient() #自動添加策略,保存服務(wù)器的主機(jī)名和密鑰信息 client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #連接SSH服務(wù)端,以用戶名和密碼進(jìn)行認(rèn)證 client.connect(ip,username=user,password=passwd) #實(shí)例化Transport,并建立會話Session ssh_session = client.get_transport().open_session() if ssh_session.active: ssh_session.exec_command(command) print ssh_session.recv(1024) client.close()
實(shí)現(xiàn)SSH服務(wù)端必須繼承ServerInterface,并實(shí)現(xiàn)里面相應(yīng)的方法。具體代碼如下:
import socket import sys import threading import paramiko host_key = paramiko.RSAKey(filename='private_key.key') class Server(paramiko.ServerInterface): def __init__(self): #執(zhí)行start_server()方法首先會觸發(fā)Event,如果返回成功,is_active返回True self.event = threading.Event() #當(dāng)is_active返回True,進(jìn)入到認(rèn)證階段 def check_auth_password(self, username, password): if (username == 'root') and (password == '123456'): return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED #當(dāng)認(rèn)證成功,client會請求打開一個Channel def check_channel_request(self, kind, chanid): if kind == 'session': return paramiko.OPEN_SUCCEEDED #命令行接收ip與port server = sys.argv[1] ssh_port = int(sys.argv[2]) #建立socket try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP socket sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((server, ssh_port)) sock.listen(100) print '[+] Listening for connection ...' client, addr = sock.accept() except Exception, e: print '[-] Listen failed: ' + str(e) sys.exit(1) print '[+] Got a connection!' try: #用sock.accept()返回的socket實(shí)例化Transport bhSession = paramiko.Transport(client) #添加一個RSA密鑰加密會話 bhSession.add_server_key(host_key) server = Server() try: #啟動SSH服務(wù)端 bhSession.start_server(server=server) except paramiko.SSHException, x: print '[-] SSH negotiation failed' chan = bhSession.accept(20) print '[+] Authenticated!' print chan.recv(1024) chan.send("Welcome to my ssh") while True: try: command = raw_input("Enter command:").strip("\n") if command != 'exit': chan.send(command) print chan.recv(1024) + '\n' else: chan.send('exit') print 'exiting' bhSession.close() raise Exception('exit') except KeyboardInterrupt: bhSession.close() except Exception, e: print '[-] Caught exception: ' + str(e) try: bhSession.close() except: pass sys.exit(1)
import paramiko #獲取Transport實(shí)例 tran = paramiko.Transport(("host_ip",22)) #連接SSH服務(wù)端 tran.connect(username = "username", password = "password") #獲取SFTP實(shí)例 sftp = paramiko.SFTPClient.from_transport(tran) #設(shè)置上傳的本地/遠(yuǎn)程文件路徑 localpath="/root/Desktop/python/NewNC.py" remotepath="/tmp/NewNC.py" #執(zhí)行上傳動作 sftp.put(localpath,remotepath) tran.close()
import paramiko #獲取SSHClient實(shí)例 client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #連接SSH服務(wù)端 client.connect("host_ip",username="username",password="password") #獲取Transport實(shí)例 tran = client.get_transport() #獲取SFTP實(shí)例 sftp = paramiko.SFTPClient.from_transport(tran) remotepath='/tmp/NewNC.py' localpath='/root/Desktop/NewNC.py' sftp.get(remotepath, localpath) client.close()
以上就是本文關(guān)于Python Paramiko模塊的使用實(shí)際案例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。