Python Paramiko模塊的使用實(shí)際案例
本文研究的主要是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不外乎從兩個(gè)角度實(shí)現(xiàn):SSH客戶端與服務(wù)端。
首先讓我們理清以下幾個(gè)名詞:
- SSHClient:包裝了Channel、Transport、SFTPClient
- Channel:是一種類Socket,一種安全的SSH傳輸通道;
- Transport:是一種加密的會(huì)話(但是這樣一個(gè)對(duì)象的Session并未建立),并且創(chuàng)建了一個(gè)加密的tunnels,這個(gè)tunnels叫做Channel;
- Session:是client與Server保持連接的對(duì)象,用connect()/start_client()/start_server()開始會(huì)話。
具體請(qǐng)參考Paramiko的庫文檔:http://docs.paramiko.org/en/2.0/index.html
下面給出幾個(gè)常用的使用案例:
SSH客戶端實(shí)現(xiàn)方案一,執(zhí)行遠(yuǎn)程命令
這個(gè)方案直接使用SSHClient對(duì)象的exec_command()在服務(wù)端執(zhí)行命令,下面是具體代碼:
#實(shí)例化SSHClient client = paramiko.SSHClient() #自動(dòng)添加策略,保存服務(wù)器的主機(jī)名和密鑰信息 client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #連接SSH服務(wù)端,以用戶名和密碼進(jìn)行認(rèn)證 client.connect(ip,username=user,password=passwd) #打開一個(gè)Channel并執(zhí)行命令 stdin,stdout,stderr = client.exec_command(command) #打印執(zhí)行結(jié)果 print stdout.readlines() #關(guān)閉SSHClient client.close()
SSH客戶端實(shí)現(xiàn)方案二,執(zhí)行遠(yuǎn)程命令
這個(gè)方案是將SSHClient建立連接的對(duì)象得到一個(gè)Transport對(duì)象,以Transport對(duì)象的exec_command()在服務(wù)端執(zhí)行命令,下面是具體代碼:
#實(shí)例化SSHClient client = paramiko.SSHClient() #自動(dòng)添加策略,保存服務(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,并建立會(huì)話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服務(wù)端的實(shí)現(xiàn)
實(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()方法首先會(huì)觸發(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會(huì)請(qǐng)求打開一個(gè)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)
#添加一個(gè)RSA密鑰加密會(huì)話
bhSession.add_server_key(host_key)
server = Server()
try:
#啟動(dòng)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)
使用SFTP上傳文件
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í)行上傳動(dòng)作
sftp.put(localpath,remotepath)
tran.close()
使用SFTP下載文件
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()
總結(jié)
以上就是本文關(guān)于Python Paramiko模塊的使用實(shí)際案例的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
相關(guān)文章
使用python爬取微博數(shù)據(jù)打造一顆“心”
這篇文章主要介紹了使用python基于微博數(shù)據(jù)打造一顆“心”,作為程序員,我準(zhǔn)備了一份特別的禮物,用以往發(fā)的微博數(shù)據(jù)打造一顆“愛心”,我想她一定會(huì)感動(dòng)得哭了吧,需要的朋友可以參考下2019-06-06
五個(gè)Jupyter?Notebook實(shí)用魔法命令分享
Jupyter?Notebook是一個(gè)開源的交互式編程環(huán)境,用于創(chuàng)建和共享包含實(shí)時(shí)代碼、文本等,本文主要來和大家分享一些有趣的Jupyter?Notebook魔法命令,需要的可以參考一下2023-07-07
Python+Selenium鍵盤鼠標(biāo)模擬事件操作詳解
這篇文章主要帶大家一起學(xué)習(xí)一下Selenium的元素的基本操作與鼠標(biāo)鍵盤模擬事件的操作,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-06-06
python 列表元素左右循環(huán)移動(dòng) 的多種解決方案
這篇文章主要介紹了python 列表元素左右循環(huán)移動(dòng) 的多種解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03
Python?pygame項(xiàng)目實(shí)戰(zhàn)監(jiān)聽退出事件
這篇文章主要介紹了Python?pygame項(xiàng)目實(shí)戰(zhàn)監(jiān)聽退出事件,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08
Python爬蟲JSON及JSONPath運(yùn)行原理詳解
這篇文章主要介紹了Python爬蟲JSON及JSONPath運(yùn)行原理詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
Python?async+request與async+aiohttp實(shí)現(xiàn)異步網(wǎng)絡(luò)請(qǐng)求探索
這篇文章主要介紹了Python?async+request與async+aiohttp實(shí)現(xiàn)異步網(wǎng)絡(luò)請(qǐng)求探索,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-10-10

