首页 > 解决方案 > 在 Paramiko 中,从列表或字典中执行命令并将结果保存到列表或字典中

问题描述

在 Paramiko 中,如何将列表或字典传递给列表或字典exec_command并将结果保存到列表或字典中?

  1. 我需要sleep在 exec_command 之间。

  2. 命令不是按顺序执行的,而是按 1、2、1 的顺序执行的。

stdin, stdout, stderr = ssh.exec_command(d.values()[0])

reuslt1 = stdout.read()

stdin, stdout, stderr = ssh.exec_command(d.values()[1])

reuslt2 = stdout.read()

stdin, stdout, stderr = ssh.exec_command(d.values()[0])

reuslt3 = stdout.read()

如果没有上面提到的两个问题,我试过map()了,效果很好。

cmd = ['xxx', 'xxx']

def func(cmd):
    stdin, stdout, stderr= ssh.exec_command(cmd)
    result = stdout.read()
    return result

list(map(func, cmd))

我的问题是我需要 SSH 远程 Linux,替换文件中的字符串。

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, password)

command = {
    "search" : "grep$img_name ='string' file",
    "modify" : "sed -i 's/$img_name = $now/$img_name = $word/g' file",
}

stdin, stdout, stderr = ssh.exec_command(command.values()[0])
before = stdout.read()
sleep(1)    ##If I don't add the wait, I will grep the string twice before the modification.
ssh.exec_command(command.values()[1])
sleep(1)
stdin, stdout, stderr = ssh.exec_command(command.values()[0])
after = stdout.read()    ##Confirm that my modification was successful
ssh.close() 

我不想重复编码stdin, stdout, stderr = ssh.exec_command()

标签: pythondictionarysshparamiko

解决方案


我相信您正在寻找这个:Iterate over dictionaries using 'for' loops

所以在 Python 3 中:

for key, value in command.items():
    stdin, stdout, stderr = ssh.exec_command(value)
    results[key] = stdout.read()

关于sleepstdout.read()不仅读取命令输出。作为读取输出的副作用,它等待命令完成。由于您不调用stdout.read(),因此sed您不必等待它完成。所以实际上,for上面的循环也应该解决这个问题,因为它等待所有命令,包括sed, 完成。


推荐阅读