Python中paramiko模塊的基礎(chǔ)操作與排錯(cuò)問(wèn)題
關(guān)于
python的ssh庫(kù)操作需要引入一個(gè)遠(yuǎn)程控制的模塊——paramiko,可用于對(duì)遠(yuǎn)程服務(wù)器進(jìn)行命令或文件操作。
應(yīng)用
登陸服務(wù)器,問(wèn)題排查??捎糜诰帉?xiě)腳本,在服務(wù)器上做一些繁瑣的重復(fù)操作。
安裝
打開(kāi)cmd,輸入命令
python -m pip install paramiko
示例
1.秘鑰登陸
配置免密登錄,linux上信任了windows的公鑰,然后腳本在windows上跑,使用windows的私鑰就可以直接不要密碼登錄linux
注意:提供秘鑰的paramiko.RSAKey.from_private_key_file('文件'),這里面的"文件"是你本機(jī)上的秘鑰,不是指你被控機(jī)上的公鑰哦!
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.單個(gè)命令執(zhí)行
1.創(chuàng)建一個(gè).py文件,引入 paramiko模塊
import paramiko
2.建立SSHClient對(duì)象
ssh = paramiko.SSHClient()
3.設(shè)置可信任,將主機(jī)加到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ā)送并獲取響應(yīng)結(jié)果
stdin, stdout, stderr = ssh.exec_command("ls /home")
print(stdout.read().decode("utf-8"))6.關(guān)閉連接
ssh.close()
3.執(zhí)行多個(gè)命令
# 執(zhí)行多條命令,注意傳入的參數(shù)有個(gè)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:
# 連接服務(wù)
transport.connect(username=user, password=psw)
# 獲取SFTP示例
sftp = paramiko.SFTPClient.from_transport(transport)
# 下載
sftp.get(remote_file, local_file)
transport.close()
問(wèn)題:(錯(cuò)誤)
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'
正確使用
要指定下載的文件名,不能只是一個(gè)目錄
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:
# 連接服務(wù)
transport.connect(username=user, password=psw)
# 獲取SFTP示例
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(local_file, remote_file)
transport.close()
測(cè)試同下載,特別要注意路徑問(wèn)題。如
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):
"""
關(guān)閉連接
: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!")
補(bǔ)充
獲取當(dāng)前文件路徑:os.getcwd()
import os
if __name__ == '__main__':
print(os.getcwd()) # D:\MyCode2\py-1\ssh
python函數(shù)返回多個(gè)參數(shù)
def get_strs() -> (str, str):
return "hello", "word"
if __name__ == '__main__':
# 返回值為元祖的形式
print(get_strs()) # ('hello', 'word')
# 獲取元祖的個(gè)數(shù)
print(len(get_strs())) # 2
# 通過(guò)下標(biāo)獲取元祖的某一個(gè)值
print(get_strs().__getitem__(1)) # word
# 通過(guò)元祖的某個(gè)元素定位對(duì)應(yīng)的下標(biāo)
print(get_strs().index("hello")) # 0
with … as …使用
為了更好地避免此類問(wèn)題,不同的編程語(yǔ)言都引入了不同的機(jī)制。在 Python 中,對(duì)應(yīng)的解決方式是使用 with as 語(yǔ)句操作上下文管理器(context manager),它能夠幫助我們自動(dòng)分配并且釋放資源。簡(jiǎn)單的理解,同時(shí)包含 enter() 和 exit() 方法的對(duì)象就是上下文管理器。
格式:
with 表達(dá)式 [as target]:
代碼塊
學(xué)習(xí)參考
- Python]遠(yuǎn)程SSH庫(kù)Paramiko簡(jiǎn)介_(kāi)alwaysrun的博客-CSDN博客_python ssh庫(kù)
- Python with as用法詳解 (biancheng.net)
- Python中的with-as用法 - 簡(jiǎn)書(shū) (jianshu.com)
到此這篇關(guān)于Python學(xué)習(xí)之paramiko模塊的基礎(chǔ)操作與排錯(cuò)的文章就介紹到這了,更多相關(guān)Python paramiko模塊內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python利用paramiko實(shí)現(xiàn)基本的SSH客戶端操作
- Python使用Paramiko實(shí)現(xiàn)輕松判斷文件類型
- Python基于paramiko庫(kù)操作遠(yuǎn)程服務(wù)器的實(shí)現(xiàn)
- Python Paramiko創(chuàng)建文件目錄并上傳文件詳解
- python的paramiko模塊基本用法詳解
- Python運(yùn)維自動(dòng)化之paramiko模塊應(yīng)用實(shí)例
- Python遠(yuǎn)程SSH庫(kù)Paramiko詳細(xì)操作
- Python使用paramiko連接遠(yuǎn)程服務(wù)器執(zhí)行Shell命令的實(shí)現(xiàn)
- python運(yùn)維自動(dòng)化Paramiko的實(shí)現(xiàn)示例
相關(guān)文章
使用Python在Word中插入圖片并文字環(huán)繞的方法
在Word文檔中插入圖片能夠提供更直觀的信息,插入圖片時(shí),我們還可以調(diào)整圖片大小,以及設(shè)置合適的文字環(huán)繞方式,本文將提供兩種使用Python在Word文檔中插入圖片并設(shè)置文字環(huán)繞的方法,需要的朋友可以參考下2024-06-06
pip search報(bào)錯(cuò)問(wèn)題及解決
這篇文章主要介紹了pip search報(bào)錯(cuò)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
如何解決jupyter?notebook中文亂碼問(wèn)題
這篇文章主要介紹了如何解決jupyter?notebook中文亂碼問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
一篇文章徹底弄懂Python中的if?__name__?==?__main__
在Python當(dāng)中如果代碼寫(xiě)得規(guī)范一些,通常會(huì)寫(xiě)上一句if '__name__'=='__main__:'作為程序的入口,下面這篇文章主要給大家介紹了關(guān)于如何通過(guò)一篇文章徹底弄懂Python中的if?__name__?==?__main__的相關(guān)資料,需要的朋友可以參考下2022-12-12
Python實(shí)現(xiàn)一元一次與一元二次方程求解
這篇文章主要為大家詳細(xì)介紹了如何利用Python實(shí)現(xiàn)一元一次與一元二次方程的求解,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-06-06
python str()如何將參數(shù)轉(zhuǎn)換為字符串類型
這篇文章主要介紹了python str()如何將參數(shù)轉(zhuǎn)換為字符串類型的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
10個(gè)使用Python必須知道的內(nèi)置函數(shù)
這篇文章小編主要向大家介紹的是10個(gè)使用Python必須知道的內(nèi)置函數(shù)reduce()、split()、map()等,更多后置函數(shù)請(qǐng)看下文2021-09-09

