最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python如何實(shí)現(xiàn)SSH遠(yuǎn)程連接與文件傳輸

 更新時(shí)間:2023年05月30日 15:02:51   作者:冰點(diǎn)契約丶  
這篇文章主要介紹了Python如何實(shí)現(xiàn)SSH遠(yuǎn)程連接與文件傳輸問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

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ù)對象,可通過 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:端口號,默認(rèn)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會話,用于將本地文件上傳到遠(yuǎn)程設(shè)備
        :param local_file_path: 本地文件絕對路徑
        :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:
        """
        打開sftp會話,用于將遠(yuǎn)程設(shè)備文件拉取到本地
        :param remote_file_path: 遠(yuǎn)程設(shè)備絕對路徑
        :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)程控制的模塊,使用該模塊可以對遠(yuǎn)程服務(wù)器進(jìn)行命令或文件操作。

安裝

使用pip可以直接安裝

pip3 install paramiko #python3

代碼

import os
import sys
import paramiko
# 創(chuàng)建SSH對象
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:
	#若用戶沒有輸入命令行參數(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è)命令用;隔開
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ù)的說明

在Linux下,當(dāng)一個(gè)用戶進(jìn)程被創(chuàng)建的時(shí)候,系統(tǒng)會自動為該進(jìn)程創(chuàng)建三個(gè)數(shù)據(jù)流,stdin, stdout 和 stderr

三個(gè)數(shù)據(jù)流默認(rèn)是表現(xiàn)在用戶終端上的

執(zhí)行一個(gè)shell命令行時(shí)通常會自動打開三個(gè)標(biāo)準(zhǔn)文件:

  • 標(biāo)準(zhǔn)輸入文件(stdin),通常對應(yīng)終端的鍵盤;
  • 標(biāo)準(zhǔn)輸出文件(stdout)和標(biāo)準(zhǔn)錯(cuò)誤輸出文件(stderr),這兩個(gè)文件都對應(yīng)終端的屏幕。

進(jìn)程將從標(biāo)準(zhǔn)輸入文件中得到輸入數(shù)據(jù),將正常輸出數(shù)據(jù)輸出到標(biāo)準(zhǔn)輸出文件,而將錯(cuò)誤信息送到標(biāo)準(zhǔn)錯(cuò)誤文件中。

證書登錄

import os
import sys
import time
import paramiko
# 創(chuàng)建SSH對象
ssh = paramiko.SSHClient()
pkey = paramiko.RSAKey.from_private_key_file('/**/**') #私鑰證書路徑
# 把要連接的機(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:
	#若用戶沒有輸入命令行參數(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, pkey=pkey)
cmd = 'cd /;ls -l;ifconfig'
# cmd = 'ls -l;ifconfig'       #多個(gè)命令用;隔開
stdin, stdout, stderr = ssh.exec_command(cmd)
time.sleep(5)#增加更多時(shí)間來處理命令
result = stdout.read()
if not result:
	result = stderr.read()
ssh.close()
print(result.decode())

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 基于Python實(shí)現(xiàn)Windows帶寬監(jiān)控工具

    基于Python實(shí)現(xiàn)Windows帶寬監(jiān)控工具

    這篇文章主要為大家詳細(xì)介紹了如何基于Python實(shí)現(xiàn)一個(gè)簡單的Windows帶寬監(jiān)控工具,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2025-09-09
  • Python matplotlib圖例放在外側(cè)保存時(shí)顯示不完整問題解決

    Python matplotlib圖例放在外側(cè)保存時(shí)顯示不完整問題解決

    這篇文章主要介紹了Python matplotlib圖例放在外側(cè)保存時(shí)顯示不完整問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • Django視圖、傳參和forms驗(yàn)證操作

    Django視圖、傳參和forms驗(yàn)證操作

    這篇文章主要介紹了Django視圖、傳參和forms驗(yàn)證操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • python比較2個(gè)xml內(nèi)容的方法

    python比較2個(gè)xml內(nèi)容的方法

    這篇文章主要介紹了python比較2個(gè)xml內(nèi)容的方法,涉及Python操作XML文件的相關(guān)技巧,需要的朋友可以參考下
    2015-05-05
  • python 模擬貸款卡號生成規(guī)則過程解析

    python 模擬貸款卡號生成規(guī)則過程解析

    這篇文章主要介紹了python 模擬貸款卡號生成規(guī)則過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • tensorflow使用指定gpu的方法

    tensorflow使用指定gpu的方法

    TensorFlow是一個(gè)基于數(shù)據(jù)流編程(dataflow programming)的符號數(shù)學(xué)系統(tǒng),被廣泛應(yīng)用于各類機(jī)器學(xué)習(xí),這篇文章主要介紹了tensorflow使用指定gpu的方法,需要的朋友可以參考下
    2020-02-02
  • Python編寫打字訓(xùn)練小程序

    Python編寫打字訓(xùn)練小程序

    這篇文章主要介紹了Python編寫打字訓(xùn)練小程序,需要的朋友可以參考下
    2019-09-09
  • Django Rest framework權(quán)限的詳細(xì)用法

    Django Rest framework權(quán)限的詳細(xì)用法

    這篇文章主要介紹了Django Rest framework權(quán)限的詳細(xì)用法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • 教你利用python實(shí)現(xiàn)企業(yè)微信發(fā)送消息

    教你利用python實(shí)現(xiàn)企業(yè)微信發(fā)送消息

    今天帶大家來練習(xí)python實(shí)戰(zhàn),文中對利用python實(shí)現(xiàn)企業(yè)微信發(fā)送消息作了詳細(xì)的圖文解說及代碼示例,對正在學(xué)習(xí)python的小伙伴很有幫助,需要的朋友可以參考下
    2021-05-05
  • Python學(xué)習(xí)筆記之線程

    Python學(xué)習(xí)筆記之線程

    這篇文章主要介紹了Python線程詳解,本文詳細(xì)講解了線程方方面面的知識,如線程基礎(chǔ)知識線程狀態(tài)、線程同步(鎖)、線程通信(條件變量)等內(nèi)容,需要的朋友可以參考下
    2021-11-11

最新評論

古浪县| 永登县| 西充县| 定南县| 东光县| 成安县| 集安市| 驻马店市| 册亨县| 黔西| 赤城县| 唐河县| 玉林市| 修文县| 石柱| 昔阳县| 乾安县| 望都县| 广宗县| 石河子市| 邳州市| 卢龙县| 越西县| 常德市| 额济纳旗| 沧州市| 昌邑市| 安国市| 延津县| 卢龙县| 保康县| 姚安县| 固阳县| 六安市| 漾濞| 庐江县| 靖西县| 深水埗区| 仪陇县| 五河县| 望城县|