-2

I want to execute some sequence of ssh commands through python script like below, (and want to display the output of the last command)

ssh hostname
sudo su userdb
cd /some/path/
./script_file -D option

I have tried with subprocess.Popen(each_command_from_list).

But it is getting stuck after connecting to hostname with ssh.

import subprocess

commands = ["ssh hostname", "sudo su userdb", "cd /some/path/", "./script_file -D option"]

for cmd in commands:
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    proc_stdout = process.communicate()[0].strip()
    if cmd.startswith("./script_file"):
        print(proc_stdout)

I expect, script should connect to hostname with ssh, and then run the commands in that host, and should get the results.

Munny
  • 37
  • 5

1 Answers1

-3

Recommend you use some sort of wrapper like Paramiko to do this.

Example usage -- Perform commands over ssh with Python

10 Rep
  • 2,217
  • 7
  • 19
  • 33
Boomer
  • 464
  • 3
  • 10
  • Thank you for the response. As mentioned in my question, I have to execute commands. Using Paramiko, have connected to ssh host and executed commands, like ssh.connect('hostname') ssh.exec_command('sudo su userdb') inp, outp, err = ssh.exec_command('/some/path/script_file -D option') But for the last command execution, I'm getting the permission error. I don't think that 'sudo su userdb' command result persists with the next command execution which may cause the permission issue. Any idea on this? – Munny Nov 08 '19 at 10:03
  • Why not just do it in a single line? `sudo su userdb && cd /some/path && ./script` – Boomer Nov 14 '19 at 22:13