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?

felicity
  • 45
  • 8
  • 1
    Possible duplicate of [Using sudo with Python script](https://stackoverflow.com/questions/13045593/using-sudo-with-python-script) – FlyingTeller Feb 06 '18 at 09:32
  • Also related: https://stackoverflow.com/questions/11955298/use-sudo-with-password-as-parameter – GPhilo Feb 06 '18 at 09:32

2 Answers2

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
AnythingIsFine
  • 1,777
  • 13
  • 11
  • 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 ? – felicity Feb 06 '18 at 09:45
  • 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. – AnythingIsFine Feb 06 '18 at 10:02
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 "abhi@192.168.0.61'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())
abhimanyu singh
  • 103
  • 1
  • 7