首頁  >  文章  >  運維  >  Python怎麼透過paramiko庫實現遠端執行linux指令

Python怎麼透過paramiko庫實現遠端執行linux指令

WBOY
WBOY轉載
2023-05-17 10:55:501493瀏覽

(1)首先安裝paramiko庫

pip install paramiko

(2)封裝了以下類,可以直接拿來使用

import paramiko

class SSHClient(object):
    def __init__(self,host,username,password,port=22):
        self.__host=host
        self.__username=username
        self.__password=password
        self.__port=port
        self.__ssh=None
        self.connect()

    def __del__(self):
        self.close()

    def connect(self):
        self.__ssh = paramiko.SSHClient()
        self.__ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.__ssh.connect(hostname=self.__host,port=self.__port,username=self.__username,password=self.__password)

    def exec(self,cmd):
        print(f"begin to run remote cmd: {cmd}")
        stdin, stdout, stderr = self.__ssh.exec_command(cmd,timeout=1800)
        returncode = stdout.channel.recv_exit_status()
        output=stdout.read().decode('utf-8')
        return output

    def close(self):
        self.__ssh.close()

(3)例如準備一個ip位址為192.168.1.12的linux虛擬機,然後直接按照以下方法使用上面封裝的類別即可實現遠端執行linux命令

ssh=SSHClient(host="192.168.1.12",username="root",password="xxxxxx")
output=ssh.exec("ifconfig")
print(output)

(4)執行結果如下

begin to run remote cmd: ifconfig
ens33: flags=41632057e901932173af9a1f1ac783f07b05  mtu 1500
        inet 192.168.1.12 195.5555.25.55road    inet6 240e:3a1:da7:6590:b39f:e15: 6b3d:7e7  prefixlen 64  scopeid 0x0c0e98daa6cc905d3cdbeafdad89e7fa3
        inet6 fe80::4a67:131d:9133:acdf  prefixlen 64 010 :0c:29:58:d8:4c  txqueuelen 1000  (Ethernet )
        RX packets 195340  bytes 148862388 (141.9 MiB)
        RX errors 0  dropped 0         RX errors 0  dropped 0         RX errors 0  dropped 0         RX errors 0  dropped 0     0   RX 5 bytes 20837281 (19.8 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73940409b266a347906f934bf7de6f943d  mtu 65536
        inet 127.0.0.1  net x10f7e6dec31ab1a0471d06c55afaca8d77

        loop txqueuelen 1000  (Local Loopback)

        RX packets 32  bytes 2592 (2.5 KiB)
       2  bytes 2592 (2.5 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

virbr0: flags=40998e6d741219daaca2222a7d10d95da900  mtu 1500
        inet road192.18500
        inet road1925.6850025.585. 192.168.122.255
        ether 52:54:00 :e8:3f:5c  txqueuelen 1000  (Ethernet)

        RX packets 0 RX bytes 0 (0.0 B)

   TX packets 0  bytes 0 (0.0 B)
TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

以上是Python怎麼透過paramiko庫實現遠端執行linux指令的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除