Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I have a script that I need to automate, so it's a .sh script which I want to run inside a python script: something like this:

import os
os.system('./script.sh -p 1234')

The script script.sh needs the user to input 3 fields, 1) the sudo password, 2) a string and 3) a string.

Enter password for user: xxxx  #typed by me
Enter Auth Username: xxxx      #typed by me
Enter Auth Password: xxx       #typed by me

How can I make the python script to type/insert/pass those 3 needed values to script.sh.

share|improve this question
    
It would be easier to modify the shell script to accept three parameters initially – Dan Apr 28 '14 at 16:51
    
yes I also thought of that, but the script changes daily and is being download from another server plus I need the sudo password. – PepperoniPizza Apr 28 '14 at 16:57
    
that does indeed complicate things – Dan Apr 28 '14 at 18:27

1 Answer 1

up vote 4 down vote accepted

You can use subprocess.Popen to start the script and the communicate method to pass it input. Something like this:

import subprocess

p = subprocess.Popen(['./script.sh', '-p', '1234'], 
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate(input='password\nauth username\nauth password\n')
share|improve this answer
    
cool, I will try this. – PepperoniPizza Apr 28 '14 at 18:44
    
I tried this, it seems to work, but I cannot tell because I can't see the script output, If I run the process with os.system() I can see the output on the python shell, nayway to get this ? – PepperoniPizza Apr 28 '14 at 19:27
    
Do you see the line where it says, stdout, stderr = p.communicate(...)? stdout contains the output from the script. – larsks Apr 28 '14 at 20:09
    
The subprocess documentation has more details about how everything works. – larsks Apr 28 '14 at 20:09
    
could you please explain me why the password\nauth ? – PepperoniPizza Apr 28 '14 at 20:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.