python paramiko模組遠端執行多條命令

2022-09-23 04:02:15 字數 936 閱讀 6387

最近一直在用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()