Switch user before executing a python script - python

I am trying to use su linux command in a python script along with getpass and subprocess python standard libraries to switch to a new user before executing my script. I am using this function:
import subprocess
import getpass
def ask_passwd():
pw = getpass.getpass(prompt='Please insert the passwd to use the auto api:') # prompt the user for a passwd
print pw
command = "su new_user"
p = subprocess.Popen(command.split(), stdin=subprocess.PIPE)
p.communicate(pw) # communicate the passwd
def main():
# code here
if __name__ == '__main__':
ask_passwd()
main()
When executing the script the main code works but not the su command. Here what I get back:
Please insert the passwd to use the auto api:
pass
su: must be run from a terminal
Any help? thanks

you may use subprocess.popen. There is an example
import subprocess
sudo_password = 'yourpassword'
command = '-i -u youruser \n id'
command = command.split()
cmd1 = subprocess.Popen(['echo', sudo_password], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['sudo', '-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)
output = cmd2.stdout.read()
print output

Related

Running a C executable inside a python program

I have written a C code where I have converted one file format to another file format. To run my C code, I have taken one command line argument : filestem.
I executed that code using : ./executable_file filestem > outputfile
Where I have got my desired output inside outputfile
Now I want to take that executable and run within a python code.
I am trying like :
import subprocess
import sys
filestem = sys.argv[1];
subprocess.run(['/home/dev/executable_file', filestem , 'outputfile'])
But it is unable to create the outputfile. I think some thing should be added to solve the > issue. But unable to figure out. Please help.
subprocess.run has optional stdout argument, you might give it file handle, so in your case something like
import subprocess
import sys
filestem = sys.argv[1]
with open('outputfile','wb') as f:
subprocess.run(['/home/dev/executable_file', filestem],stdout=f)
should work. I do not have ability to test it so please run it and write if it does work as intended
You have several options:
NOTE - Tested in CentOS 7, using Python 2.7
1. Try pexpect:
"""Usage: executable_file argument ("ex. stack.py -lh")"""
import pexpect
filestem = sys.argv[1]
# Using ls -lh >> outputfile as an example
cmd = "ls {0} >> outputfile".format(filestem)
command_output, exitstatus = pexpect.run("/usr/bin/bash -c '{0}'".format(cmd), withexitstatus=True)
if exitstatus == 0:
print(command_output)
else:
print("Houston, we've had a problem.")
2. Run subprocess with shell=true (Not recommended):
"""Usage: executable_file argument ("ex. stack.py -lh")"""
import sys
import subprocess
filestem = sys.argv[1]
# Using ls -lh >> outputfile as an example
cmd = "ls {0} >> outputfile".format(filestem)
result = subprocess.check_output(shlex.split(cmd), shell=True) # or subprocess.call(cmd, shell=True)
print(result)
It works, but python.org frowns upon this, due to the chance of a shell injection: see "Security Considerations" in the subprocess documentation.
3. If you must use subprocess, run each command separately and take the SDTOUT of the previous command and pipe it into the STDIN of the next command:
p = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE)
stdout_data, stderr_data = p.communicate()
p = subprocess.Popen(cmd, stdin=stdout_data, stdout=PIPE)
etc...
Good luck with your code!

Responding to an input when executing a python script through SSH

I am currently using a windows machine and trying to SSH to an Ubuntu Server, using PKI. I need to run the python script test.py using the sudo command. The script contains an input that will ask me for a number after running test.py. I have tried putting for a number after the sudo command but it did not work.
import subprocess
command = "ssh -t john#x.x.x.x echo 'john' | sudo -S python3.7 ./Desktop/test.py"
command = command.split()
out = subprocess.check_output(["scp", "test.py", "john#x.x.x.x:./Desktop"])
run_script = subprocess.run(command, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
Example of test.py:
import subprocess
choice = input("Choose a number: ")
if choice == 1:
result = subprocess.run(['cat' '/etc/passwd'], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
print(result.stdout.decode('utf-8'))
How can I respond to this input and where should I put it in my code?
If your remote command's standard input is connected to your Python script, simply use that.
run_script = subprocess.run(command,
stdout = subprocess.PIPE, stderr = subprocess.PIPE,
input="1\n", text=True)
I'm guessing you'll want to capture the output with capture=True, and probably also add check=True to the keyword arguments as well.
The addition of text=True saves you from having to encnde your input into bytes, and similarly from having to decode the output.

how to run a command in python, supplying input, then reading the output

I want to use Popen from subprocess
to execute the command: 'python3 test.py'
# The following is test.py code:
string = input('Enter Something')
if string == 'mypassword':
print('Success')
else:
print('Fail')
In my program, I want to execute 'python3 test.py' multiple times, each time supplying input, and reading the output ('Success' or 'Fail') and storing it in a variable.
My program that is suppose to execute 'python3 test.py' is as follows:
from subprocess import Popen, PIPE
# Runs test.py
command = Popen(['python3', 'test.py'], stdin=PIPE)
# After this, it prompts me to type in the input,
# but I want to supply it from a variable
# I want to do something like
my_input = 'testpassword'
command.supplyInput(my_input)
result = command.getOutput()
# result will have the string value of 'Success' or 'Fail'
You can add parameter stdout=PIPE to Popen, and use Popen.communicate to supply input and read the output instead.
from subprocess import Popen, PIPE
command = Popen(['python3', 'test.py'], stdin=PIPE, stdout=PIPE)
my_input = 'testpassword\n'
result, _ = command.communicate(my_input)
Please read Popen.communicate's documentation for more details:
https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate

How to show user aliases in python

I am trying to make a scrip in python to show the aliases of a user I picked just like when you type alias in the terminal.
so far the code goes like this:
tt = open("/etc/passwd" , "r")
with tt as f2:
with open("passwd" , "w+") as f1:
f1.write(f2.read())
f1.seek(0,0)
command = f1.read()
print
print command
chose = raw_input("select user's name from this list > ")
rootlist = "1) Show user groups \n2) Show user id \n3) Show users alias\n4) Add new alias \n5) Change Password \n6) Back"
print
print rootlist
print
chose2 = int(raw_input("Choose a command > "))
if choose == 3:
os.system("alias ")
however os.system("alias ") doesn't work and I can't seem to find a proper way t do it.
Alias is a shell builtin which can be seen here
$ type -a alias
alias is a shell builtin
This is the problem, which you can solve by adding a call to bash to your shell command
import os
os.system('bash -i -c "alias"')
or the preferred way using subprocess module
from subprocess import Popen, PIPE, STDOUT
cmd = 'bash -i -c "alias"'
event = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
output = event.communicate()[0]
print(output)

getting subprocess result in variable

I am executing python script using subprocess.call() in pytho script. The script which gets executed using subproecss is a server process which send result back to calling client.
result = subprocess.call('python -m module/coref_resolution/src/coref/corenlp &', shell = True)
Is there any way to receive result from corenlp.py into result variable?
import shlex
cmd = shlex.split('your command')
output = subprocess.Popen( cmd, stdout = subprocess.PIPE).communicate()[0]

Categories

Resources