2

I want to call a .sh file from a python script. This requires sudo permissions and I want to automatically pass the password without getting a prompt. I tried using subprocess.

(VAR1 is variable I want to pass, permissions.sh is the sh file I want to call from python script)

process = subprocess.Popen(['sudo', './permissions.sh', VAR1], stdin = subprocess.PIPE, stdout = subprocess.PIPE)
process.communicate(password)

Then I tried using pexpect

child = pexpect.spawn('sudo ./permissions.sh'+VAR1)
child.sendline(password)

In both cases it still prompts for password on the terminal. I want to pass the password automatically. I do not want to use os modules. How can this be done?

2

2 Answers 2

1

would use pexpect, but you need to tell it what to expect after the sudo as so:

#import the pexpect module
import pexpect
# here you issue the command with "sudo"
child = pexpect.spawn('sudo /usr/sbin/lsof')
# it will prompt something like: "[sudo] password for < generic_user >:"
# you "expect" to receive a string containing keyword "password"
child.expect('password')
# if it's found, send the password
child.sendline('S3crEt.P4Ss')
# read the output
print(child.read())
# the end
Sign up to request clarification or add additional context in comments.

2 Comments

I made the changes to the code as you suggested. However, if I just add the expect line, the code won't work. But adding the last line, i.e. print child.read() does the work. Could you explain why ?
Yes, the print(child.read() line merely prints out the result of your command, if it's not printed it does not mean it wasn't executed.
0
# use python3 for pexpect module e.g python3 myscript.py
import pexpect
# command with "sudo"
child = pexpect.spawn('sudo rm -f')
# it will prompt a line like "[email protected]'s password:"
# as the word 'password' appears in the line pass it as argument to expect
child.expect('password')
# enter the password
child.sendline('mypassword')
# must be there
child.interact()
# output
print(child.read())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.