Python Paramiko模塊的使用實際案例
本文研究的主要是Python Paramiko模塊的使用的實例,具體如下。
Windows下有很多非常好的SSH客戶端,比如Putty。在python的世界里,你可以使用原始套接字和一些加密函數(shù)創(chuàng)建自己的SSH客戶端或服務端,但如果有現(xiàn)成的模塊,為什么還要自己實現(xiàn)呢。使用Paramiko庫中的PyCrypto能夠讓你輕松使用SSH2協(xié)議。
Paramiko的安裝方法網上有很多這樣的帖子,這里就不描述了。這里主要講如何使用它。Paramiko實現(xiàn)SSH2不外乎從兩個角度實現(xiàn):SSH客戶端與服務端。
首先讓我們理清以下幾個名詞:
- SSHClient:包裝了Channel、Transport、SFTPClient
- Channel:是一種類Socket,一種安全的SSH傳輸通道;
- Transport:是一種加密的會話(但是這樣一個對象的Session并未建立),并且創(chuàng)建了一個加密的tunnels,這個tunnels叫做Channel;
- Session:是client與Server保持連接的對象,用connect()/start_client()/start_server()開始會話。
具體請參考Paramiko的庫文檔:http://docs.paramiko.org/en/2.0/index.html
下面給出幾個常用的使用案例:
SSH客戶端實現(xiàn)方案一,執(zhí)行遠程命令
這個方案直接使用SSHClient對象的exec_command()在服務端執(zhí)行命令,下面是具體代碼:
#實例化SSHClient client = paramiko.SSHClient() #自動添加策略,保存服務器的主機名和密鑰信息 client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #連接SSH服務端,以用戶名和密碼進行認證 client.connect(ip,username=user,password=passwd) #打開一個Channel并執(zhí)行命令 stdin,stdout,stderr = client.exec_command(command) #打印執(zhí)行結果 print stdout.readlines() #關閉SSHClient client.close()
SSH客戶端實現(xiàn)方案二,執(zhí)行遠程命令
這個方案是將SSHClient建立連接的對象得到一個Transport對象,以Transport對象的exec_command()在服務端執(zhí)行命令,下面是具體代碼:
#實例化SSHClient client = paramiko.SSHClient() #自動添加策略,保存服務器的主機名和密鑰信息 client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #連接SSH服務端,以用戶名和密碼進行認證 client.connect(ip,username=user,password=passwd) #實例化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()
SSH服務端的實現(xiàn)
實現(xiàn)SSH服務端必須繼承ServerInterface,并實現(xiàn)里面相應的方法。具體代碼如下:
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()
#當is_active返回True,進入到認證階段
def check_auth_password(self, username, password):
if (username == 'root') and (password == '123456'):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
#當認證成功,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實例化Transport
bhSession = paramiko.Transport(client)
#添加一個RSA密鑰加密會話
bhSession.add_server_key(host_key)
server = Server()
try:
#啟動SSH服務端
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)
使用SFTP上傳文件
import paramiko
#獲取Transport實例
tran = paramiko.Transport(("host_ip",22))
#連接SSH服務端
tran.connect(username = "username", password = "password")
#獲取SFTP實例
sftp = paramiko.SFTPClient.from_transport(tran)
#設置上傳的本地/遠程文件路徑
localpath="/root/Desktop/python/NewNC.py"
remotepath="/tmp/NewNC.py"
#執(zhí)行上傳動作
sftp.put(localpath,remotepath)
tran.close()
使用SFTP下載文件
import paramiko
#獲取SSHClient實例
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#連接SSH服務端
client.connect("host_ip",username="username",password="password")
#獲取Transport實例
tran = client.get_transport()
#獲取SFTP實例
sftp = paramiko.SFTPClient.from_transport(tran)
remotepath='/tmp/NewNC.py'
localpath='/root/Desktop/NewNC.py'
sftp.get(remotepath, localpath)
client.close()
總結
以上就是本文關于Python Paramiko模塊的使用實際案例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
使用python爬取微博數(shù)據(jù)打造一顆“心”
這篇文章主要介紹了使用python基于微博數(shù)據(jù)打造一顆“心”,作為程序員,我準備了一份特別的禮物,用以往發(fā)的微博數(shù)據(jù)打造一顆“愛心”,我想她一定會感動得哭了吧,需要的朋友可以參考下2019-06-06
python 列表元素左右循環(huán)移動 的多種解決方案
這篇文章主要介紹了python 列表元素左右循環(huán)移動 的多種解決方案,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
Python?pygame項目實戰(zhàn)監(jiān)聽退出事件
這篇文章主要介紹了Python?pygame項目實戰(zhàn)監(jiān)聽退出事件,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08
Python?async+request與async+aiohttp實現(xiàn)異步網絡請求探索
這篇文章主要介紹了Python?async+request與async+aiohttp實現(xiàn)異步網絡請求探索,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2022-10-10

