Python如何實(shí)現(xiàn)SSH遠(yuǎn)程連接與文件傳輸
Python SSH遠(yuǎn)程連接與文件傳輸
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 查看參數(shù)傳遞幫助 :param help_info: """ super(Args, self).__init__(description=help_info) def __call__(self, *args, **kwargs): """ :param args: :param kwargs: :return: 返回參數(shù)對(duì)象,可通過(guò) args.xxx 獲取參數(shù) """ 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:遠(yuǎn)程ip地址 :param username:用戶名 :param password:密碼 :param port:端口號(hào),默認(rèn)22 """ self.ip = ip_address self.username = username self.password = password self.port = port self.__client = SSHClient() def connect(self) -> None: """ 打開(kāi)連接 :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: """ 打開(kāi)sftp會(huì)話,用于將本地文件上傳到遠(yuǎn)程設(shè)備 :param local_file_path: 本地文件絕對(duì)路徑 :param remote_file_path: 遠(yuǎn)程文件路徑:命名方式: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: """ 打開(kāi)sftp會(huì)話,用于將遠(yuǎn)程設(shè)備文件拉取到本地 :param remote_file_path: 遠(yuǎn)程設(shè)備絕對(duì)路徑 :param local_save_path: 本地文件保存路徑 命名方式:file +filename 注意需要指定文件名,否則報(bào)錯(cuò) :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í)行命令結(jié)果
調(diào)用paramiko模塊
paramiko是一個(gè)用于做遠(yuǎn)程控制的模塊,使用該模塊可以對(duì)遠(yuǎn)程服務(wù)器進(jìn)行命令或文件操作。
安裝
使用pip可以直接安裝
pip3 install paramiko #python3
代碼
import os import sys import paramiko # 創(chuàng)建SSH對(duì)象 ssh = paramiko.SSHClient() # 把要連接的機(jī)器添加到known_hosts文件中 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 輸入?yún)?shù)并進(jìn)行判斷 if len(sys.argv) == 4: ip = sys.argv[1] uname = sys.argv[2] passwd = sys.argv[3] else: #若用戶沒(méi)有輸入命令行參數(shù),則提示用戶 print("Invalid amount of arguments.") print("example:python3 ssh.py <ip> <uname> <passwd>") sys.exit() # 連接服務(wù)器 # 用戶名密碼 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' #多個(gè)命令用;隔開(kāi) stdin, stdout, stderr = ssh.exec_command(cmd) result = stdout.read() if not result: result = stderr.read() ssh.close() print(result.decode())
關(guān)于linux中stdin, stdout, stderr三個(gè)參數(shù)的說(shuō)明
在Linux下,當(dāng)一個(gè)用戶進(jìn)程被創(chuàng)建的時(shí)候,系統(tǒng)會(huì)自動(dòng)為該進(jìn)程創(chuàng)建三個(gè)數(shù)據(jù)流,stdin, stdout 和 stderr
三個(gè)數(shù)據(jù)流默認(rèn)是表現(xiàn)在用戶終端上的
執(zhí)行一個(gè)shell命令行時(shí)通常會(huì)自動(dòng)打開(kāi)三個(gè)標(biāo)準(zhǔn)文件:
- 標(biāo)準(zhǔn)輸入文件(stdin),通常對(duì)應(yīng)終端的鍵盤(pán);
- 標(biāo)準(zhǔn)輸出文件(stdout)和標(biāo)準(zhǔn)錯(cuò)誤輸出文件(stderr),這兩個(gè)文件都對(duì)應(yīng)終端的屏幕。
進(jìn)程將從標(biāo)準(zhǔn)輸入文件中得到輸入數(shù)據(jù),將正常輸出數(shù)據(jù)輸出到標(biāo)準(zhǔn)輸出文件,而將錯(cuò)誤信息送到標(biāo)準(zhǔn)錯(cuò)誤文件中。
證書(shū)登錄
import os import sys import time import paramiko # 創(chuàng)建SSH對(duì)象 ssh = paramiko.SSHClient() pkey = paramiko.RSAKey.from_private_key_file('/**/**') #私鑰證書(shū)路徑 # 把要連接的機(jī)器添加到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: #若用戶沒(méi)有輸入命令行參數(shù),則提示用戶 print("Invalid amount of arguments.") print("example:python3 ssh.py <ip> <uname> <passwd>") sys.exit() # 連接服務(wù)器 # 私鑰證書(shū)登錄 ssh.connect(hostname=ip, port=22, username=uname, pkey=pkey) cmd = 'cd /;ls -l;ifconfig' # cmd = 'ls -l;ifconfig' #多個(gè)命令用;隔開(kāi) stdin, stdout, stderr = ssh.exec_command(cmd) time.sleep(5)#增加更多時(shí)間來(lái)處理命令 result = stdout.read() if not result: result = stderr.read() ssh.close() print(result.decode())
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- 如何使用Python連接?SSH?服務(wù)器并執(zhí)行命令
- python paramiko連接ssh實(shí)現(xiàn)命令
- Python基于ssh遠(yuǎn)程連接Mysql數(shù)據(jù)庫(kù)操作
- Python用SSH連接到網(wǎng)絡(luò)設(shè)備
- Python3 SSH遠(yuǎn)程連接服務(wù)器的方法示例
- python下paramiko模塊實(shí)現(xiàn)ssh連接登錄Linux服務(wù)器
- Python實(shí)現(xiàn)建立SSH連接的方法
- Python自動(dòng)連接ssh的方法
- Python自動(dòng)連接SSH的實(shí)現(xiàn)步驟
相關(guān)文章
python編程中簡(jiǎn)潔優(yōu)雅的推導(dǎo)式示例詳解
這篇文章主要為大家介紹了python編程中簡(jiǎn)潔優(yōu)雅的推導(dǎo)式示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11Python實(shí)現(xiàn)的微信公眾號(hào)群發(fā)圖片與文本消息功能實(shí)例詳解
這篇文章主要介紹了Python實(shí)現(xiàn)的微信公眾號(hào)群發(fā)圖片與文本消息功能,結(jié)合實(shí)例形式詳細(xì)分析了Python調(diào)用微信接口實(shí)現(xiàn)微信公眾號(hào)群發(fā)圖片與文本消息的具體操作步驟與相關(guān)注意事項(xiàng),需要的朋友可以參考下2017-06-06Python的Pandas時(shí)序數(shù)據(jù)詳解
這篇文章主要為大家詳細(xì)介紹了Pandas時(shí)序數(shù)據(jù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-03-03使用python的pandas為你的股票繪制趨勢(shì)圖
這篇文章主要介紹了通過(guò)python為你的股票繪制趨勢(shì)圖,動(dòng)手寫(xiě)個(gè)小程序, 把股票趨勢(shì)每天早上發(fā)到郵箱里,用 python 的 pandas, matplotlib 寫(xiě)起來(lái)很容易, 幾十行代碼搞定。,需要的朋友可以參考下2019-06-06詳解如何使用Pandas刪除DataFrame中的非數(shù)字類型數(shù)據(jù)
在數(shù)據(jù)處理和分析過(guò)程中,經(jīng)常會(huì)遇到需要清洗數(shù)據(jù)的情況,本文將詳細(xì)介紹如何使用Pandas刪除DataFrame中的非數(shù)字類型數(shù)據(jù),感興趣的小伙伴可以了解下2024-03-03使用python快速實(shí)現(xiàn)不同機(jī)器間文件夾共享方式
今天小編就為大家分享一篇使用python快速實(shí)現(xiàn)不同機(jī)器間文件夾共享方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12