1

In Paramiko, how to pass a list or dict to exec_command and save results to a list or dict?

  1. I need sleep between exec_command.

  2. Commands are not executed sequentially, but in the order of 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()

If there are no two problems mentioned above, I have tried map(), it works fine.

cmd = ['xxx', 'xxx']

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

list(map(func, cmd))

My problem is that I need to SSH a remote Linux, replace a string in a file.

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() 

I don't want to repeat coding stdin, stdout, stderr = ssh.exec_command().

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Xuesong Ye
  • 505
  • 5
  • 13

1 Answers1

0

I believe you are looking for this: Iterating over dictionaries using 'for' loops.

So in Python 3:

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

Regarding the sleep: The stdout.read() not only reads a command output. It, as an side effect of reading the output, waits for the command to finish. As you do not call stdout.read() for the sed, you do not wait for it to finish. So actually, the for loop above should solve that problem too, as it waits for all commands, including the sed, to finish.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • Thank you for modifying the question, great. I tried your suggestion. But, Do you mean that I don't need to check if it is changed after the modification? – Xuesong Ye Sep 13 '18 at 11:07
  • I didn't wrote that. If you want to repeat the `grep`, add a third entry to the `command` dictionary. – Martin Prikryl Sep 14 '18 at 07:22