0

I am trying to update the router with a python script with only one ssh call. However, the kill() function is executed before the update starts.

process_1 = f' opkg update'
process_2 = f' echo process 2'

cmds = [
    f'{process_1}\n',
    f'{process_2}'
]

proc = subprocess.Popen(["ssh", "root@192.168.1.1"], stdin=subprocess.PIPE)

for cmd in cmds:
    proc.stdin.write(f'{cmd}'.encode())

proc.stdin.flush()
proc.stdin.close()
proc.kill()
tripleee
  • 175,061
  • 34
  • 275
  • 318
gubwan
  • 3
  • 2

2 Answers2

0

Solution

.wait() is the method I was looking for

process_1 = f' opkg update'
process_2 = f' echo process 2'

cmds = [
    f'{process_1}\n',
    f'{process_2}'
]

proc = subprocess.Popen(["ssh", "root@192.168.1.1"], stdin=subprocess.PIPE)

for cmd in cmds:
    proc.stdin.write(f'{cmd}'.encode())

proc.stdin.flush()
proc.stdin.close()
proc.wait()
gubwan
  • 3
  • 2
0

Passing commands to standard input of ssh is somewhat finicky. A much better solution is to switch to Paramiko, but if your needs are simple, just refactor to pass the commands as arguments to ssh.

result = subprocess.run(
    ["ssh", "root@192.168.1.1",
     "\n".join(cmds)],
    check=True)

Like the documentation already tells you, you should generally prefer subprocess.run (or its legacy siblings check_call, check_output, etc) over Popen whenever you can. The problems you were experiencing is one of the symptoms, and of course, the fixed code is also much shorter and easier to understand.

As a further aside, f'{thing}' is just a really clumsy way to write thing (or str(thing) if thing isn't already a string).

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • subprocess.run(["ssh", "root@192.168.1.1","\n".join(cmds)],check=True) is awesome, thanks! Trying to figure out how to deal with non-zero exit status. – gubwan Jul 01 '22 at 13:25
  • Just remove the `check=True` if you don't want failure to trigger a traceback. For further details, see also https://stackoverflow.com/questions/4256107/running-bash-commands-in-python/51950538#51950538 – tripleee Jul 01 '22 at 15:00