python paramiko 支持使用cd的ssh交互式命令下发

import paramiko
import time


class CONSSH:
    def __init__(self, host, username, password, port=22):
        self.__ssh = paramiko.SSHClient()
        self.__ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.__ssh.connect(host, username=username, password=password, port=port)
        self.channel = self.__ssh.invoke_shell(width=1000, height=100) # 此处尽量使长命令行输出在一行,如果需要限制命令回显每行长度可以在此处修改
        time.sleep(2)
        self.exec_cmd("echo 'connnect success'")

    def exec_cmd(self, command):
        self.channel.send(command + "
")
        time.sleep(0.5)
        return self.channel.recv(1024).decode()
    

def __exit__(self, exc_type, exc_val, exc_tb): self.__ssh.close()

def __enter__(self): return self if __name__ == "__main__": with CONSSH("ip", "user", "pwd") as s: res = s.exec_cmd("ls /etc") print(res)

尽量使用with实例化类,防止忘记关闭句柄

可以直接使用,但是健壮性较差,如果需要提高健壮性在连接、下发命令处使用try捕捉异常即可

原文地址:https://www.cnblogs.com/yingyingdeyueer/p/14295510.html