Python中paramiko模塊的基礎操作與排錯問題
關于
python的ssh庫操作需要引入一個遠程控制的模塊——paramiko,可用于對遠程服務器進行命令或文件操作。
應用
登陸服務器,問題排查。可用于編寫腳本,在服務器上做一些繁瑣的重復操作。
安裝
打開cmd,輸入命令
python -m pip install paramiko
示例
1.秘鑰登陸
配置免密登錄,linux上信任了windows的公鑰,然后腳本在windows上跑,使用windows的私鑰就可以直接不要密碼登錄linux
注意
:提供秘鑰的paramiko.RSAKey.from_private_key_file('文件')
,這里面的"文件"是你本機上的秘鑰,不是指你被控機上的公鑰哦!
import paramiko key = paramiko.RSAKey.from_private_key_file("C:\\Users\\liyansheng\\.ssh\\id_rsa") ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) print("connecting") ssh.connect(hostname="192.168.220.128", username="root", pkey=key) print("connected") commands = "uname -a" stdin, stdout, stderr = ssh.exec_command(commands) stdin.close() res, err = stdout.read(), stderr.read() result = res if res else err print(result) ssh.close() if __name__ == '__main__': print()
2.單個命令執(zhí)行
1.創(chuàng)建一個.py
文件,引入 paramiko
模塊
import paramiko
2.建立SSHClient
對象
ssh = paramiko.SSHClient()
3.設置可信任,將主機加到host_allow
列表
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
4.創(chuàng)建連接
ssh.connect("150.158.16.123", 22, "wuyanping", "2022")
5.創(chuàng)建命令,發(fā)送并獲取響應結果
stdin, stdout, stderr = ssh.exec_command("ls /home") print(stdout.read().decode("utf-8"))
6.關閉連接
ssh.close()
3.執(zhí)行多個命令
# 執(zhí)行多條命令,注意傳入的參數(shù)有個list def execMultiCmd(host, user, psw, cmds: list, port=22) -> (str, str): with paramiko.SSHClient() as ssh_client: ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=host, port=port, username=user, password=psw) cmd = ";".join(cmds) _, stdout, stderr = ssh_client.exec_command(cmd, get_pty=True) result = stdout.read().decode('utf-8') err = stderr.read().decode('utf-8') return result, err if __name__ == '__main__': cmdList = ["cd /home", "ls"] print(execMultiCmd("192.168.220.128", "root", "root", cmdList))
4.SFTPClient下載文件
方法封裝:
def down_file(host, user, psw, local_file, remote_file, port=22): with paramiko.Transport((host, port)) as transport: # 連接服務 transport.connect(username=user, password=psw) # 獲取SFTP示例 sftp = paramiko.SFTPClient.from_transport(transport) # 下載 sftp.get(remote_file, local_file) transport.close()
問題:(錯誤)
if __name__ == '__main__': down_file(my_linux.host, my_linux.user, my_linux.psw, "D:\\ssh_download", "/home/test.txt")
Traceback (most recent call last): File "D:\MyCode2\py-1\ssh\download.py", line 17, in <module> down_file("192.168.220.128", "root", "root", "D:\\ssh_download", "/home/test.txt") File "D:\MyCode2\py-1\ssh\download.py", line 11, in down_file sftp.get(remote_file, local_file) File "D:\MyCode2\py-1\venv\lib\site-packages\paramiko\sftp_client.py", line 810, in get with open(localpath, "wb") as fl: PermissionError: [Errno 13] Permission denied: 'D:\\ssh_download'
正確使用
要指定下載的文件名,不能只是一個目錄
if __name__ == '__main__': down_file(my_linux.host, my_linux.user, my_linux.psw, "D:\\ssh_download\\test.txt", "/home/test.txt")
5.上傳文件
def upload_file(host, user, psw, local_file, remote_file, port=22): with paramiko.Transport((host, port)) as transport: # 連接服務 transport.connect(username=user, password=psw) # 獲取SFTP示例 sftp = paramiko.SFTPClient.from_transport(transport) sftp.put(local_file, remote_file) transport.close()
測試同下載,特別要注意路徑問題
。如
if __name__ == '__main__': upload_file(my_linux.host, my_linux.user, my_linux.psw, "D:\\ssh_download\\test123.txt", "/home/test/test123.txt")
6.ssh工具封裝
import os import paramiko class SSHTool(): def __init__(self, ip, port, user, psw): """ 初始化 :param ip: :param port: :param user: :param psw: """ self.ip = ip self.port = port self.user = user self.psw = psw def connect_ssh(self): """ 創(chuàng)建連接 :return: """ try: self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect( hostname=self.ip, port=self.port, username=self.user, password=self.psw ) except Exception as e: print(e) return self.ssh def close_ssh(self): """ 關閉連接 :return: """ try: self.ssh.close() except Exception as e: print(e) def exec_shell(self, shell): ssh = self.connect_ssh() try: stdin, stdout, stderr = ssh.exec_command(shell) return stdin, stdout, stderr except Exception as e: print(e) def sftp_put_file(self, file, local_dir, remote_dir): try: t = paramiko.Transport((self.ip, self.port)) t.connect(username=self.user, password=self.psw) sftp = paramiko.SFTPClient.from_transport(t) sftp.put(os.path.join(local_dir, file), remote_dir) t.close() except Exception: print("connect error!") def sftp_get_file(self, file, local_dir, remote_dir): try: t = paramiko.Transport((self.ip, self.port)) t.connect(username=self.user, password=self.psw) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(remote_dir, os.path.join(local_dir, file)) t.close() except Exception: print("connect error!")
補充
獲取當前文件路徑:os.getcwd()
import os if __name__ == '__main__': print(os.getcwd()) # D:\MyCode2\py-1\ssh
python函數(shù)返回多個參數(shù)
def get_strs() -> (str, str): return "hello", "word" if __name__ == '__main__': # 返回值為元祖的形式 print(get_strs()) # ('hello', 'word') # 獲取元祖的個數(shù) print(len(get_strs())) # 2 # 通過下標獲取元祖的某一個值 print(get_strs().__getitem__(1)) # word # 通過元祖的某個元素定位對應的下標 print(get_strs().index("hello")) # 0
with … as …使用
為了更好地避免此類問題,不同的編程語言都引入了不同的機制。在 Python 中,對應的解決方式是使用 with as 語句操作上下文管理器(context manager),它能夠幫助我們自動分配并且釋放資源。簡單的理解,同時包含 enter() 和 exit() 方法的對象就是上下文管理器。
格式:
with 表達式 [as target]: 代碼塊
學習參考
- Python]遠程SSH庫Paramiko簡介_alwaysrun的博客-CSDN博客_python ssh庫
- Python with as用法詳解 (biancheng.net)
- Python中的with-as用法 - 簡書 (jianshu.com)
到此這篇關于Python學習之paramiko模塊的基礎操作與排錯的文章就介紹到這了,更多相關Python paramiko模塊內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Python使用Paramiko庫實現(xiàn)SSH管理詳解
- python的paramiko模塊基本用法詳解
- Python通過paramiko庫實現(xiàn)遠程執(zhí)行l(wèi)inux命令的方法
- Python運維自動化之paramiko模塊應用實例
- Python遠程SSH庫Paramiko詳細操作
- python 第三方庫paramiko的常用方式
- Python如何實現(xiàn)Paramiko的二次封裝
- python 使用paramiko模塊進行封裝,遠程操作linux主機的示例代碼
- Python paramiko使用方法代碼匯總
- Python Paramiko模塊中exec_command()和invoke_shell()兩種操作區(qū)別
相關文章
tensorflow之變量初始化(tf.Variable)使用詳解
今天小編就為大家分享一篇tensorflow之變量初始化(tf.Variable)使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python實現(xiàn)http接口自動化測試的示例代碼
這篇文章主要介紹了Python實現(xiàn)http接口自動化測試的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10Pytorch測試神經(jīng)網(wǎng)絡時出現(xiàn) RuntimeError:的解決方案
這篇文章主要介紹了Pytorch測試神經(jīng)網(wǎng)絡時出現(xiàn) RuntimeError:的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05Python Socket TCP雙端聊天功能實現(xiàn)過程詳解
這篇文章主要介紹了Python Socket TCP雙端聊天功能實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06