Python利用paramiko實(shí)現(xiàn)基本的SSH客戶端操作
簡(jiǎn)介
??paramiko?? 是一個(gè)用于進(jìn)行 SSH2 協(xié)議編程的 Python 庫,它支持加密和認(rèn)證功能,可以用來實(shí)現(xiàn)安全的遠(yuǎn)程命令執(zhí)行和文件傳輸。本文將通過幾個(gè)實(shí)例來介紹如何使用 ??paramiko?? 進(jìn)行基本的 SSH 客戶端操作。
安裝 Paramiko
在使用 ??paramiko?? 之前,需要先安裝該庫??梢酝ㄟ^ ??pip?? 命令輕松安裝:
pip install paramiko
基本使用
創(chuàng)建 SSH 客戶端連接
首先,我們需要?jiǎng)?chuàng)建一個(gè) SSH 客戶端對(duì)象,并通過該對(duì)象連接到遠(yuǎn)程服務(wù)器。
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username='username', password='password')
??set_missing_host_key_policy(paramiko.AutoAddPolicy())??:設(shè)置自動(dòng)添加策略,用于添加和保存服務(wù)器的 SSH 密鑰。
??connect()?? 方法用于連接到指定的主機(jī),需要提供主機(jī)名、用戶名和密碼。
執(zhí)行遠(yuǎn)程命令
連接成功后,可以使用 ??exec_command()?? 方法來執(zhí)行遠(yuǎn)程命令。
stdin, stdout, stderr = ssh.exec_command('ls /home')
print(stdout.read().decode())
??exec_command()?? 返回三個(gè)對(duì)象:??stdin??(標(biāo)準(zhǔn)輸入)、??stdout??(標(biāo)準(zhǔn)輸出)和 ??stderr??(標(biāo)準(zhǔn)錯(cuò)誤)。
使用 ??stdout.read().decode()?? 可以讀取命令的輸出并解碼為字符串格式。
文件傳輸
除了執(zhí)行命令,??paramiko?? 還支持文件的上傳和下載。這可以通過 ??SFTP?? 功能實(shí)現(xiàn)。
上傳文件
sftp = ssh.open_sftp()
sftp.put('/path/to/local/file', '/path/to/remote/file')
sftp.close()
??open_sftp()?? 方法打開 SFTP 會(huì)話。
??put()?? 方法用于上傳本地文件到遠(yuǎn)程服務(wù)器。
最后調(diào)用 ??close()?? 方法關(guān)閉 SFTP 會(huì)話。
下載文件
sftp = ssh.open_sftp()
sftp.get('/path/to/remote/file', '/path/to/local/file')
sftp.close()
??get()?? 方法用于從遠(yuǎn)程服務(wù)器下載文件到本地。
關(guān)閉連接
完成所有操作后,記得關(guān)閉 SSH 連接以釋放資源。
ssh.close()
高級(jí)用法
使用密鑰認(rèn)證
除了使用密碼認(rèn)證,??paramiko?? 還支持使用私鑰進(jìn)行身份驗(yàn)證。
private_key = paramiko.RSAKey.from_private_key_file('/path/to/private/key')
ssh.connect('hostname', username='username', pkey=private_key)
??RSAKey.from_private_key_file()?? 方法從指定路徑加載私鑰文件。
在 ??connect()?? 方法中使用 ??pkey?? 參數(shù)傳遞私鑰對(duì)象。
處理命令輸出
在執(zhí)行遠(yuǎn)程命令時(shí),有時(shí)需要處理命令的標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤。可以通過檢查 ??stdout?? 和 ??stderr?? 來實(shí)現(xiàn)這一點(diǎn)。
stdin, stdout, stderr = ssh.exec_command('command')
output = stdout.read().decode()
error = stderr.read().decode()
if error:
print(f"Error: {error}")
else:
print(f"Output: {output}")
檢查 ??stderr?? 的內(nèi)容,如果存在則打印錯(cuò)誤信息。
如果沒有錯(cuò)誤,則打印命令的輸出。
知識(shí)補(bǔ)充
??paramiko??? 提供了強(qiáng)大的功能來處理 SSH 連接,無論是執(zhí)行遠(yuǎn)程命令還是文件傳輸,都非常方便。通過本文的幾個(gè)實(shí)例,希望讀者能夠?qū)???paramiko??? 的基本用法有一個(gè)初步的了解,并能夠在實(shí)際項(xiàng)目中應(yīng)用這些知識(shí)。以上是關(guān)于 ??paramiko??? 庫的基本使用教程,包括如何安裝、創(chuàng)建 SSH 連接、執(zhí)行命令、文件傳輸以及一些高級(jí)用法。??paramiko??? 是一個(gè)用于在 Python 中進(jìn)行 SSH2 協(xié)議編程的強(qiáng)大庫,常用于遠(yuǎn)程服務(wù)器管理和自動(dòng)化任務(wù)。下面我將提供幾個(gè)實(shí)際應(yīng)用場(chǎng)景中的 ??paramiko??
示例代碼:
1. 遠(yuǎn)程執(zhí)行命令
假設(shè)你需要定期從遠(yuǎn)程服務(wù)器獲取系統(tǒng)信息,比如 CPU 使用率、內(nèi)存使用情況等。
import paramiko
# 創(chuàng)建 SSH 客戶端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連接到遠(yuǎn)程服務(wù)器
ssh.connect('192.168.1.100', username='user', password='password')
# 執(zhí)行命令
stdin, stdout, stderr = ssh.exec_command('top -b -n 1')
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')
# 打印輸出
print("Output:\n", output)
if error:
print("Error:\n", error)
# 關(guān)閉連接
ssh.close()2. 上傳和下載文件
假設(shè)你需要將本地文件上傳到遠(yuǎn)程服務(wù)器,或者從遠(yuǎn)程服務(wù)器下載文件。
import paramiko
# 創(chuàng)建 SSH 客戶端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連接到遠(yuǎn)程服務(wù)器
ssh.connect('192.168.1.100', username='user', password='password')
# 創(chuàng)建 SFTP 會(huì)話
sftp = ssh.open_sftp()
# 上傳文件
local_path = '/path/to/local/file.txt'
remote_path = '/path/to/remote/file.txt'
sftp.put(local_path, remote_path)
# 下載文件
remote_path = '/path/to/remote/file.txt'
local_path = '/path/to/local/file.txt'
sftp.get(remote_path, local_path)
# 關(guān)閉 SFTP 會(huì)話和 SSH 連接
sftp.close()
ssh.close()3. 動(dòng)態(tài)配置管理
假設(shè)你需要在多臺(tái)服務(wù)器上動(dòng)態(tài)配置環(huán)境變量或修改配置文件。
import paramiko
# 創(chuàng)建 SSH 客戶端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連接到遠(yuǎn)程服務(wù)器
ssh.connect('192.168.1.100', username='user', password='password')
# 修改配置文件
command = "echo 'export PATH=$PATH:/new/path' >> ~/.bashrc"
stdin, stdout, stderr = ssh.exec_command(command)
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')
# 打印輸出
print("Output:\n", output)
if error:
print("Error:\n", error)
# 重新加載配置文件
command = "source ~/.bashrc"
stdin, stdout, stderr = ssh.exec_command(command)
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')
# 打印輸出
print("Output:\n", output)
if error:
print("Error:\n", error)
# 關(guān)閉連接
ssh.close()4. 遠(yuǎn)程日志監(jiān)控
假設(shè)你需要實(shí)時(shí)監(jiān)控遠(yuǎn)程服務(wù)器上的日志文件,并在出現(xiàn)特定錯(cuò)誤時(shí)發(fā)送通知。
import paramiko
import time
# 創(chuàng)建 SSH 客戶端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連接到遠(yuǎn)程服務(wù)器
ssh.connect('192.168.1.100', username='user', password='password')
# 打開日志文件
command = "tail -f /var/log/syslog"
stdin, stdout, stderr = ssh.exec_command(command)
# 實(shí)時(shí)讀取日志
try:
while True:
line = stdout.readline()
if line:
print(line.strip())
# 檢查特定錯(cuò)誤
if "ERROR" in line:
print("Error detected: ", line.strip())
# 發(fā)送通知(例如通過郵件或消息服務(wù))
except KeyboardInterrupt:
print("Monitoring stopped.")
# 關(guān)閉連接
ssh.close()這些示例展示了 ??paramiko?? 在不同場(chǎng)景下的應(yīng)用,希望對(duì)你有所幫助!
paramiko?? 是一個(gè)用于在 Python 中實(shí)現(xiàn) SSH2 協(xié)議的庫,它允許你遠(yuǎn)程連接到其他機(jī)器并執(zhí)行命令、傳輸文件等。下面我將詳細(xì)介紹如何使用 ??paramiko?? 創(chuàng)建一個(gè) SSH 客戶端,并通過示例代碼來展示其基本用法。
1. 安裝 Paramiko
首先,你需要安裝 ??paramiko?? 庫??梢酝ㄟ^ ??pip?? 來安裝:
pip install paramiko
2. 基本用法
導(dǎo)入庫
import paramiko
創(chuàng)建 SSH 客戶端
ssh = paramiko.SSHClient()
自動(dòng)添加未知主機(jī)密鑰
為了簡(jiǎn)化操作,你可以設(shè)置 ??SSHClient?? 自動(dòng)添加未知主機(jī)的密鑰到本地 ??known_hosts?? 文件中:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
連接到遠(yuǎn)程服務(wù)器
使用 ??connect?? 方法連接到遠(yuǎn)程服務(wù)器。你需要提供主機(jī)名(或 IP 地址)、用戶名和密碼(或私鑰):
ssh.connect('hostname_or_ip', username='username', password='password')
或者使用私鑰文件:
private_key = paramiko.RSAKey.from_private_key_file('/path/to/private/key')
ssh.connect('hostname_or_ip', username='username', pkey=private_key)
執(zhí)行命令
連接成功后,可以使用 ??exec_command?? 方法執(zhí)行命令:
stdin, stdout, stderr = ssh.exec_command('ls /home')
print(stdout.read().decode())
上傳和下載文件
使用 ??SFTP?? 會(huì)話來上傳和下載文件:
sftp = ssh.open_sftp()
sftp.put('/local/path/to/file', '/remote/path/to/file') # 上傳文件
sftp.get('/remote/path/to/file', '/local/path/to/file') # 下載文件
sftp.close()
關(guān)閉連接
完成所有操作后,記得關(guān)閉 SSH 連接:
ssh.close()
完整示例
下面是一個(gè)完整的示例,展示了如何連接到遠(yuǎn)程服務(wù)器、執(zhí)行命令并上傳/下載文件:
import paramiko
# 創(chuàng)建 SSH 客戶端
ssh = paramiko.SSHClient()
# 自動(dòng)添加未知主機(jī)密鑰
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連接到遠(yuǎn)程服務(wù)器
ssh.connect('hostname_or_ip', username='username', password='password')
# 執(zhí)行命令
stdin, stdout, stderr = ssh.exec_command('ls /home')
print("Output of 'ls /home':")
print(stdout.read().decode())
# 上傳文件
sftp = ssh.open_sftp()
sftp.put('/local/path/to/file', '/remote/path/to/file')
print("File uploaded successfully.")
# 下載文件
sftp.get('/remote/path/to/file', '/local/path/to/file')
print("File downloaded successfully.")
# 關(guān)閉 SFTP 會(huì)話
sftp.close()
# 關(guān)閉 SSH 連接
ssh.close()注意事項(xiàng)
安全性:使用密碼連接時(shí),確保密碼的安全性。如果可能,使用密鑰對(duì)進(jìn)行身份驗(yàn)證。
錯(cuò)誤處理:在實(shí)際應(yīng)用中,建議添加異常處理機(jī)制,以應(yīng)對(duì)網(wǎng)絡(luò)問題或其他異常情況。
資源管理:確保在操作完成后關(guān)閉 SFTP 會(huì)話和 SSH 連接,以釋放資源。
到此這篇關(guān)于Python利用paramiko實(shí)現(xiàn)基本的SSH客戶端操作的文章就介紹到這了,更多相關(guān)Python paramiko使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python獲取excel內(nèi)容及相關(guān)操作代碼實(shí)例
這篇文章主要介紹了Python獲取excel內(nèi)容及相關(guān)操作代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
使用Python進(jìn)行Ping測(cè)試的操作指南
在網(wǎng)絡(luò)工程中,Ping測(cè)試是一種常用的網(wǎng)絡(luò)診斷工具,用于檢查網(wǎng)絡(luò)連接的可達(dá)性和響應(yīng)時(shí)間,隨著Python編程語言的廣泛應(yīng)用,越來越多的網(wǎng)絡(luò)工程師開始使用Python進(jìn)行自動(dòng)化網(wǎng)絡(luò)測(cè)試和管理任務(wù),本篇文章將詳細(xì)介紹如何使用Python進(jìn)行Ping測(cè)試,需要的朋友可以參考下2024-06-06
Python爬蟲實(shí)現(xiàn)使用beautifulSoup4爬取名言網(wǎng)功能案例
這篇文章主要介紹了Python爬蟲實(shí)現(xiàn)使用beautifulSoup4爬取名言網(wǎng)功能,結(jié)合實(shí)例形式分析了Python基于beautifulSoup4模塊爬取名言網(wǎng)并存入MySQL數(shù)據(jù)庫相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
詳解Python下Flask-ApScheduler快速指南
Flask是Python社區(qū)非常流行的一個(gè)Web開發(fā)框架,本文將嘗試將介紹APScheduler應(yīng)用于Flask之中,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2018-11-11
Python如何用NumPy讀取和保存點(diǎn)云數(shù)據(jù)
這篇文章主要介紹了Python如何用NumPy讀取和保存點(diǎn)云數(shù)據(jù),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08
pandas數(shù)據(jù)處理基礎(chǔ)之篩選指定行或者指定列的數(shù)據(jù)
這篇文章主要介紹了pandas數(shù)據(jù)處理基礎(chǔ)之篩選指定行或者指定列的數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2018-05-05
Python使用Pickle模塊進(jìn)行數(shù)據(jù)保存和讀取的講解
今天小編就為大家分享一篇關(guān)于Python使用Pickle模塊進(jìn)行數(shù)據(jù)保存和讀取的講解,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-04-04
Django項(xiàng)目單字段區(qū)間查詢的實(shí)現(xiàn)
在Django項(xiàng)目中會(huì)碰到一些需求就是查詢某個(gè)表中的一些字段從某日到某日的數(shù)據(jù),你可以像在SQL中那樣使用SELECT語句來查找指定字段,本文就來介紹兩種方法,感興趣的可以了解一下2023-10-10

