joseph
joseph

Reputation: 123

Python script to execute external commands

I need to issue some commands to the currently executing program and get the output of the current (remotely) executing program into some string in the script. The problem I am currently encountering is that I don't know the output of each command which output can also vary as it can be read from user.

e.g.

  1. ./my_program
  2. print_output_1 [ with in my_program ]
  3. print_output_2 [ with in my_program ]
  4. exit [ with in my_program ]

and if i run the commands manually terminal will get something like this

bash$ ./my_programe
my_program: print_output_1
my_program:first_line_printed_with_unknown_length
my_program: print_output_2
my_program:second_line_printed_with_unknown_length
my_program: exit
bash$

so i should get "first_line_printed_with_unknown_length" and "second_line_printed_with_unknown_length" in a python string like

execute(my_program)
str1 = execute( print_output_1 )
str2 = execute( print_output_2 )
val = execute( exit )

Upvotes: 1

Views: 756

Answers (2)

Juxhin
Juxhin

Reputation: 5620

You can make use of the subprocess module to execute external commands. It is best to start with much simpler commands first to get the gist of it all. Below is a dummy example:

import subprocess
from subprocess import PIPE

def main():
    process = subprocess.Popen('echo %USERNAME%', stdout=PIPE, shell=True)
    username = process.communicate()[0]
    print username #prints the username of the account you're logged in as

if __name__ == '__main__':
    main()

This will grab the output from echo %USERNAME% and store it. Pretty simply to give you the general idea.

From the aforementioned documentation:

Warning: Using shell=True can be a security hazard. See the warning under Frequently Used Arguments for details.

Upvotes: 1

shevron
shevron

Reputation: 3673

It is possible to do with ssh (i.e. the ssh command), and ssh, like any shell-executable command can be wrapped in Python, so the answer is yes. Something like this could work (I did not try though):

import subprocess

remote_command = ['ls', '-l']
ssh_command = ['ssh', '[email protected]'] + remote_command
proc = subprocess.Popen(ssh_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

# stdout now contains the output of the remote command
# stderr now contains the error stream from the remote command or from ssh

You can also use Paramiko which is an ssh implementation in Python, but that might be overkill if you do not need interactivity.

Upvotes: 0

Related Questions