欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python paramiko模块远程执行多条命令

程序员文章站 2022-03-20 14:00:58
...

最近一直在用python的paramiko执行远程命令,发现如果直接写的话在每条命令后加分号执行时会报错,如果不加分号,分一条命令一条命令地执行,起不到作用,如切换路径等,后面在网上找到了相关的方法,只要在exec_command(cmd,get_pty=True)在命令语句后加get_pty=True即可。代码如下:

    def exec_command(self,cmd):
        client = paramiko.SSHClient()
        try:
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(self.hostip, self.port, username=self.username, password=self.pwd, timeout=20)
            stdin, stdout, stderr = client.exec_command(cmd,get_pty=True)
            # logWriteToTxt(self.sitename + "执行"+cmd)
            res=""
            results = stdout.readlines()

            for line in results:
                res+=line
            try:
                err=stderr.readlines()
                for line in err:
                    res+=line
            except:
                pass
                # results = stdout.readlines()
            # logWriteToTxt("在" + self.sitename + "执行"+cmd + res)

            return res
        except:
            pass
        finally:
            client.close()