1. 程式人生 > 程式設計 >Python paramiko模組使用解析(實現ssh)

Python paramiko模組使用解析(實現ssh)

開發堡壘機之前,先來學習Python的paramiko模組,該模組基於SSH用於連線遠端伺服器並執行相關操作

安裝paramiko模組

pip3 install paramiko

基於使用者密碼方式

import paramiko

# 建立SSH物件
ssh = paramiko.SSHClient()
# 允許連線不在know_hosts檔案中的主機
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連線伺服器
ssh.connect(hostname="10.0.0.200",port=22,username='root',password='1')

# 執行命令
# stdin:標準輸入(就是你輸入的命令);stdout:標準輸出(就是命令執行結果);stderr:標準錯誤(命令執行過程中如果出錯了就把錯誤打到這裡),stdout和stderr僅會輸出一個
stdin,stdout,stderr = ssh.exec_command('df')
# 獲取命令結果
result = (stdout.read().decode('utf-8'))  # 這個有問題,如果執行的命令是錯誤的,會不顯示錯誤,可以修改一下,先判斷stdout有沒有值,如果輸出沒有,就顯示錯誤
print(result)
# 關閉連線
ssh.close()

基於公鑰金鑰連線

import paramiko

# 指定私鑰路徑
private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')

# 建立SSH物件
ssh = paramiko.SSHClient()
# 允許連線不在know_hosts檔案中的主機
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連線伺服器
ssh.connect(hostname='10.0.0.171',pkey=private_key)

# 執行命令
stdin,stderr = ssh.exec_command('df')
# 獲取命令結果
result = stdout.read()
print(result.decode())
# 關閉連線
ssh.close()

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。