網站首頁 編程語言 正文
運維自動化Python
paramiko模塊
一、模塊介紹
模塊:paramiko
模塊作用:
1、通過ssh協議遠程執行命令
2、文件上傳下載
安裝模塊:
pip install paramiko
二、模塊應用
1.使用paramiko模塊,通過ssh協議連接服務器
#導入paramiko,(導入前需要先在環境里安裝該模塊)
import paramiko
#定義函數ssh,把操作內容寫到函數里
def sshExeCMD():
#定義一個變量ssh_clint
ssh_client=paramiko.SSHClient()
#使用cnnect類來連接服務器
ssh_client.connect(hostname="192.168.1.110", port="22", username="songxk", password="123123")
#通過判斷模塊名運行上邊函數
if __name__ == '__main__':
sshExeCMD()
這時會報錯,提示在服務器的known_hosts中沒有,這個就是連接服務器的時候那個首次連接需要輸入一個yes保存證書。
2.解決首次連接known_hosts問題
通過這個set_missing_host_key_policy方法用于實現登錄是需要確認輸入yes,否則保存
#導入paramiko,(導入前需要先在環境里安裝該模塊)
import paramiko
#定義函數ssh,把操作內容寫到函數里
def sshExeCMD():
#定義一個變量ssh_clint
ssh_client=paramiko.SSHClient()
#通過這個set_missing_host_key_policy方法用于實現登錄是需要確認輸入yes,否則保存
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#使用cnnect類來連接服務器
ssh_client.connect(hostname="192.168.1.110", port="22", username="songxk", password="123123")
#通過判斷模塊名運行上邊函數
if __name__ == '__main__':
sshExeCMD()
連接成功, 沒有報錯:
3、執行命令exec_command方法
使用exec_command執行命令會返回三個信息:
1、標準輸入內容(用于實現交互式命令)
2、標準輸出(保存命令的正常執行結果)
3、標準錯誤輸出(保存命令的錯誤信息)
可以通過三個變量來接受,然后使用print輸出到屏幕查看
#導入paramiko,(導入前需要先在環境里安裝該模塊)
import paramiko
#定義函數ssh,把操作內容寫到函數里
def sshExeCMD():
#定義一個變量ssh_clint使用SSHClient類用來后邊調用
ssh_client=paramiko.SSHClient()
#通過這個set_missing_host_key_policy方法用于實現登錄是需要確認輸入yes,否則保存
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#使用cnnect類來連接服務器
ssh_client.connect(hostname="192.168.1.110", port="22", username="songxk", password="123123")
#使用exec_command方法執行命令,并使用變量接收命令的返回值并用print輸出
stdin, stdout, stderr = ssh_client.exec_command("hostname")
print(stdout.read())
#通過判斷模塊名運行上邊函數
if __name__ == '__main__':
sshExeCMD()
展示內容以python的格式b’內容\n’的格式展示,如果后邊需要對回顯處理,可以直接用str把內容輸出為字符串格式如下:
print(str(stdout.read()))
擴展:
使用try異常捕獲
import paramiko
import sys
#定義函數ssh,把操作內容寫到函數里
def sshExeCMD():
#定義一個變量ssh_clint使用SSHClient類用來后邊調用
ssh_client=paramiko.SSHClient()
#通過這個set_missing_host_key_policy方法用于實現登錄是需要確認輸入yes,否則保存
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#使用try做異常捕獲
try:
#使用cnnect類來連接服務器
ssh_client.connect(hostname="192.168.1.110", port="22", username="songx1k", password="123123")
#如果上邊命令報錯吧報錯信息定義到err變量,并輸出。
except Exception as err:
print("服務器鏈接失敗!!!")
print(err)
#如果報錯使用sys的exit退出腳本
sys.exit()
#使用exec_command方法執行命令,并使用變量接收命令的返回值并用print輸出
stdin, stdout, stderr = ssh_client.exec_command("df -hT")
print(str(stdout.read()))
#通過判斷模塊名運行上邊函數
if __name__ == '__main__':
sshExeCMD()
4、多臺服務器執行命令
注意:給函數傳參,需要在函數括號里寫上接收的參數
#導入paramiko,(導入前需要先在環境里安裝該模塊)
import paramiko
import sys
#定義函數ssh,把操作內容寫到函數里,函數里接收參數(寫在括號里),其中port=是設置一個默認值如果沒傳就用默認
def sshExeCMD(ip, username, password, port=22):
#定義一個變量ssh_clint使用SSHClient類用來后邊調用
ssh_client=paramiko.SSHClient()
#通過這個set_missing_host_key_policy方法用于實現登錄是需要確認輸入yes,否則保存
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#使用try做異常捕獲
try:
#使用cnnect類來連接服務器
ssh_client.connect(hostname=ip, port=port, username=username, password=password)
#如果上邊命令報錯吧報錯信息定義到err變量,并輸出。
except Exception as err:
print("服務器鏈接失敗!!!"% ip)
print(err)
#如果報錯使用sys的exit退出腳本
sys.exit()
#使用exec_command方法執行命令,并使用變量接收命令的返回值并用print輸出
#這里也可以把命令做成參數傳進來
stdin, stdout, stderr = ssh_client.exec_command("hostname")
#使用decode方法可以指定編碼
print(stdout.read().decode("utf-8"))
#通過判斷模塊名運行上邊函數
if __name__ == '__main__':
#定義一個字典,寫服務器信息
servers = {
#以服務器IP為鍵,值為服務器的用戶密碼端口定義的字典
"192.168.1.110": {
"username": "songxk",
"password": "123123",
"port": 22,
},
"192.168.1.123": {
"username": "root",
"password": "123123",
"port": 22,
},
}
#使用items方法遍歷,使用ip 和info把字典里的鍵和值遍歷賦值,傳給函數sshExeCMD
for ip, info in servers.items():
# 這里的info也就是上邊定義的ip對應值的字典,使用get獲取這個字典里對應username鍵對應的值,賦值給變量username傳給函數中使用
sshExeCMD(
ip=ip,
username=info.get("username"),
password=info.get("password"),
port=info.get("port")
)
5、從服務器上傳下載文件–SFTPClient方法
'''
通過ssh協議在服務器上傳下載文
時間:2022-04-09
'''
import paramiko
def sshfileftp():
#與服務器創建ssh連接,transport方法建立通道,以元組的方式歇服務器信息
ssh_conn = paramiko.Transport(("192.168.1.110", 60317))
ssh_conn.connect(username="songxk", password="123123")
#創建連接后,使用sftpclient類和from_transport(括號里寫上邊創建的Transport通道)基于上邊ssh連接創建一個sftp連接,定義成ftp_client變量后邊方便引用
ftp_client = paramiko.SFTPClient.from_transport(ssh_conn)
#下載文件
#ftp_client.get("目標文件", r"保存位置,寫到文件名")
ftp_client.get("/etc/fstab", r"C:\Users\Administrator.USER-CH3G0KO3MG\Desktop\test\fstab")
'''
上傳文件
ftp_client.put(r"C:\Users\Administrator.USER-CH3G0KO3MG\Desktop\test\fstab", "/etc/fstab")
'''
#關閉ssh連接
ssh_conn.close()
if __name__ == '__main__':
sshfileftp()
6、多臺服務器上傳下載文件
和批量對服務器執行命令原理一樣,使用字典寫服務器信息,通過for循環處理把變量分別傳給寫好的上傳函數。
'''
批量通過ssh協議在服務器上傳文件
時間:2022-04-09
localfile:本地文件名
remotedir:服務器目錄名
'''
import paramiko
#后續需要用到os模塊的方法
import os
#定義函數并且接收變量
def sshPutfile(ip, port, username, password, localfile, remotedir):
#獲取源文件的文件名,把進來的localfile變量的值處理只剩文件名
file_name = os.path.basename(localfile)
#處理服務器目錄名,如果輸入的目錄名沒有帶后邊的/(不是以/結尾)則添加一個,方便后邊拼接文件名
if not remotedir.endswith("/"):
remotedir = remotedir + "/"
dest_file_name = remotedir + file_name
#創建ssh連接
ssh_conn = paramiko.Transport((ip, port))
ssh_conn.connect(username=username, password=password)
#創建ftp工具(變量)
ftp_client = paramiko.SFTPClient.from_transport(ssh_conn)
#上傳文件
ftp_client.put(localfile, dest_file_name)
# 關閉ssh連接
ssh_conn.close()
if __name__ == '__main__':
#定義一個字典,寫服務器的信息
servers = {
#以服務器IP為鍵,值為服務器的用戶密碼端口定義的字典
"192.168.1.110": {
"username": "songxk",
"password": "123123",
"port": 60317,
},
"192.168.106.71": {
"username": "root",
"password": "123123",
"port": 22,
},
}
source_file = input("請輸入源文件路徑(絕對路徑):")
remote_dir = input("服務器路徑(絕對路徑):")
for ip, info in servers.items():
sshPutfile(
ip=ip,
port=info.get("port"),
username=info.get("username"),
password=info.get("password"),
localfile=source_file,
remotedir=remote_dir
)
效果:
擴展-文件操作
對文件的操作除了上傳下載還有其他很多操作
可擴展練習
1、 輸入的文件是否存在
2、服務器目錄是否存在
3、上傳后文件是否完整(利用md5判斷,本地文件的md5和Linux命令md5sum)
總結
原文鏈接:https://blog.csdn.net/Sxiaokun/article/details/124070120
相關推薦
- 2022-06-01 C++的matlab接口轉換方法詳解_C 語言
- 2023-01-01 Golang反射修改變量值的操作代碼_Golang
- 2022-08-10 詳細聊一聊algorithm中的排序算法_C 語言
- 2022-07-18 SQL?Server中的數據類型詳解_MsSql
- 2022-12-09 Go?Web實戰之創建項目及增加日志功能_Golang
- 2022-06-02 CKAD認證中部署k8s并配置Calico插件_云和虛擬化
- 2022-07-26 Python的基本數據類型
- 2022-10-01 python3中_from...import...與import?...之間的區別詳解(包/模塊)_
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支