python3 --Paramiko 远程连接服务器,并同时执行多条shell命令

import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, port, username, password, timeout=10)
for i in range(10):
    curr = get_value(0, i + 1, 1)
    tx =  get_value(0, i + 1, 3)
    shell = 'test.py '  +  curr  + '  --tx  ' + tx
    #print (shell)
    stdin, stdout, stderr =client.exec_command('cd path;pwd' + ';' + shell,get_pty=True)
    for std in stdout.readlines():
        #print(std)
        with open('result.txt','a') as f:        #a,以追踪的方式写入
            f.write(std)
    for std in stderr.readlines():
        with open('err.txt','a') as f:
            f.write(stderr)
client.close()

paramiko.SSHClient().exec_command() 可以执行一条命令;当执行多条命令时,多条命令放在一个单引号下面,各命令之间用分号隔开,且在末尾加上get_pty=True。当多条命令中有参数时,可以这么写client.exec_command('cd path;pwd' + ';' + shell,get_pty=True)  shell 是参数。


猜你喜欢

转载自blog.csdn.net/only_anan/article/details/80055624