zoukankan      html  css  js  c++  java
  • 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捕捉异常即可

  • 相关阅读:
    jmap之使用说明与JVM配置
    Linux之tomcat日志管理
    服务器连接数与资源监控
    Git命令之资源
    状态机
    分布式之消息系统架构
    Memcache之内存分配机制
    LRU算法
    Linux(Ubuntu)之设定开机自启动
    mysql 查询 优化
  • 原文地址:https://www.cnblogs.com/yingyingdeyueer/p/14295510.html
Copyright © 2011-2022 走看看