Python如何實現SSH遠程連接與文件傳輸
更新時間:2023年05月30日 15:02:51 作者:冰點契約丶
這篇文章主要介紹了Python如何實現SSH遠程連接與文件傳輸問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
Python SSH遠程連接與文件傳輸
from paramiko import (SSHClient, SFTPClient, AutoAddPolicy)
import argparse
class Args(argparse.ArgumentParser):
def __init__(self, help_info: str = "remote host login args"):
"""
使用 python xx.py -h 查看參數傳遞幫助
:param help_info:
"""
super(Args, self).__init__(description=help_info)
def __call__(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return: 返回參數對象,可通過 args.xxx 獲取參數
"""
self.add_argument("--ip", help="remote host ip address")
self.add_argument("--username", help="SSH login username", default="")
self.add_argument("--password", help="SSH login password", default="")
self.add_argument("--port", help="remote host port", default=22)
return self.parse_args()
class SSH(object):
def __init__(self, ip_address: str, username: str, password: str, port: int = 22):
"""
:param ip_address:遠程ip地址
:param username:用戶名
:param password:密碼
:param port:端口號,默認22
"""
self.ip = ip_address
self.username = username
self.password = password
self.port = port
self.__client = SSHClient()
def connect(self) -> None:
"""
打開連接
:return:None
"""
self.__client.set_missing_host_key_policy(AutoAddPolicy())
self.__client.connect(self.ip, self.port, self.username, self.password)
def execute(self, command: str) -> None:
"""
執(zhí)行命令,stderr未啟用
:param command: windows命令
:return: None
"""
std_in, stdout, stderr = self.__client.exec_command(command=command)
print(stdout.read().decode("utf-8"))
def upload_file(self, local_file_path: str, remote_file_path: str) -> None:
"""
打開sftp會話,用于將本地文件上傳到遠程設備
:param local_file_path: 本地文件絕對路徑
:param remote_file_path: 遠程文件路徑:命名方式:path+filename
:return:
"""
sftp: SFTPClient = self.__client.open_sftp()
try:
sftp.put(localpath=local_file_path, remotepath=remote_file_path)
print(f"file:{local_file_path} upload success!")
except Exception as e:
print(f"upload file file,please check whether the file path is correct!\nerror massage:{e} ")
def download_file(self, remote_file_path: str, local_save_path) -> None:
"""
打開sftp會話,用于將遠程設備文件拉取到本地
:param remote_file_path: 遠程設備絕對路徑
:param local_save_path: 本地文件保存路徑 命名方式:file +filename 注意需要指定文件名,否則報錯
:return:
"""
sftp: SFTPClient = self.__client.open_sftp()
try:
sftp.get(remotepath=remote_file_path, localpath=local_save_path)
print(f"file:{remote_file_path} download success!")
except Exception as e:
print(f"upload file file,please check whether the file path is correct!\nerror massage:{e} ")
def get_shell(self) -> None:
"""
獲取shell
:return:
"""
while True:
command = input(f"{self.ip}@{self.username}$:")
if command.__eq__("quit"):
break
self.execute(command=command)
def __del__(self):
print("Disconnected!")
self.__client.close()Python建立ssh連接并返回shell執(zhí)行命令結果
調用paramiko模塊
paramiko是一個用于做遠程控制的模塊,使用該模塊可以對遠程服務器進行命令或文件操作。
安裝
使用pip可以直接安裝
pip3 install paramiko #python3
代碼
import os
import sys
import paramiko
# 創(chuàng)建SSH對象
ssh = paramiko.SSHClient()
# 把要連接的機器添加到known_hosts文件中
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 輸入參數并進行判斷
if len(sys.argv) == 4:
ip = sys.argv[1]
uname = sys.argv[2]
passwd = sys.argv[3]
else:
#若用戶沒有輸入命令行參數,則提示用戶
print("Invalid amount of arguments.")
print("example:python3 ssh.py <ip> <uname> <passwd>")
sys.exit()
# 連接服務器
# 用戶名密碼
ssh.connect(hostname=ip, port=22, username=uname, password=passwd)
#ssh.connect(hostname='xxx.xxx.xx.xx', port=22, username='xxx', password='xxx')
cmd = 'cd /;ls -l;ifconfig'
# cmd = 'ls -l;ifconfig' #多個命令用;隔開
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read()
if not result:
result = stderr.read()
ssh.close()
print(result.decode())關于linux中stdin, stdout, stderr三個參數的說明
在Linux下,當一個用戶進程被創(chuàng)建的時候,系統(tǒng)會自動為該進程創(chuàng)建三個數據流,stdin, stdout 和 stderr
三個數據流默認是表現在用戶終端上的
執(zhí)行一個shell命令行時通常會自動打開三個標準文件:
- 標準輸入文件(stdin),通常對應終端的鍵盤;
- 標準輸出文件(stdout)和標準錯誤輸出文件(stderr),這兩個文件都對應終端的屏幕。
進程將從標準輸入文件中得到輸入數據,將正常輸出數據輸出到標準輸出文件,而將錯誤信息送到標準錯誤文件中。
證書登錄
import os
import sys
import time
import paramiko
# 創(chuàng)建SSH對象
ssh = paramiko.SSHClient()
pkey = paramiko.RSAKey.from_private_key_file('/**/**') #私鑰證書路徑
# 把要連接的機器添加到known_hosts文件中
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if len(sys.argv) == 3:
ip = sys.argv[1]
uname = sys.argv[2]
#passwd = sys.argv[3]
else:
#若用戶沒有輸入命令行參數,則提示用戶
print("Invalid amount of arguments.")
print("example:python3 ssh.py <ip> <uname> <passwd>")
sys.exit()
# 連接服務器
# 私鑰證書登錄
ssh.connect(hostname=ip, port=22, username=uname, pkey=pkey)
cmd = 'cd /;ls -l;ifconfig'
# cmd = 'ls -l;ifconfig' #多個命令用;隔開
stdin, stdout, stderr = ssh.exec_command(cmd)
time.sleep(5)#增加更多時間來處理命令
result = stdout.read()
if not result:
result = stderr.read()
ssh.close()
print(result.decode())總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python調用帶空格的windows?cmd命令問題及連續(xù)運行多個命令方式
這篇文章主要介紹了python調用帶空格的windows?cmd命令問題及連續(xù)運行多個命令方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02

