Rum cmd from python subprocess module with admin privileges - python

I would like to know if there is any way to run a cmd process using subprocess module in python(Using Popen) with admin privileges. I need to run some conmmand that must have admin privileges in order to run correctly.
Thanks in advance!!

from the link
Set administrator privileges to subprocess.check_call() in Python
import subprocess as sp
sp.check_call(['DoesnotNeedAdminPrivilege.exe'])
prog = sp.Popen(['runas', '/noprofile', '/user:Administrator', 'NeedsAdminPrivilege.exe'],stdin=sp.PIPE)
prog.stdin.write('password')
prog.communicate()

Related

How to run sudo commands in shell/linux using python script

How to run sudo bash using python script
import subprocess
import os
sudoPassword2 = 'abcd1234'
command2 = 'sudo bash'
p2 = os.system('echo %s|sudo -S %s' % (sudoPassword2, command2))
I'm getting this error:
bash: line 1: abcd1234: command not found
when i tried to this also its giving error
import shlex
import subprocess
command1 = shlex.split('cd /home/backups')
subprocess.call(command1)
error cd no file or dir
tried also this :
import shlex
import subprocess
subprocess.call(["cd","/home","/backups"])
You can use os module
import os
os.system("sudo and the code you want to run")
in example:
import os
os.system("sudo apt-get vlc")
You are receiving this error because your command posts the password to the cli first without being asked for it. So bash will interpret it as a command which, obviously, can not be executed.
Better do os.system('sudo command') and call the script as root or via sudo. This will make sure you have the necessary privileges within the script immediately at run time.
Another reason why you definitely want to refrain from doing what you do is the necessity of having the sudo password for your machine written into the script in plain text. Never do that. It's evil.
If there is no way around you can make sudo execute a command without asking for a password by adding NOPASSWD directives to the /etc/sudoers by using the editor visudo (never use anything different) like so:
user host = (root) NOPASSWD: /sbin/shutdown
user host = (root) NOPASSWD: /sbin/reboot
But if you do make sure you know that this opens the execution of this command to anyone on the system without needing elevated rights. This can be a huge security risk.

Calling Matlab scripts from Django with Python's Popen class

I'm developing a Django app which runs Matlab scripts with Python's Popen class. The python script that calls Matlab scripts lives in the main folder of my Django app (with views.py). When I call the script from command line, it runs like a charm but when I make a request from the client in order to run the corresponding python script, I receive the following warning:
"< M A T L A B (R) > Copyright 1984-2018 The MathWorks, Inc. R2018a (9.4.0.813654) 64-bit (glnxa64) February 23, 2018 To get started, type one of these: helpwin, helpdesk, or demo. For product information, visit www.mathworks.com. >> [Warning: Unable to create preferences folder in /var/www/.matlab/R2018a. Preferences folder location must be writable. Using a temporary preferences folder for this MATLAB session. See the preferences documentation for more details.] >>
My app uses a Python virtual environment and it is being deployed with Apache web server.
Here is my python script that calls Matlab scripts:
import os
import subprocess as sp
import pymat_config
def pymat_run():
pwd = pymat_config.pwd_config['pwd']
cmd1 = "-r \"Arg_in = '/path/to/my/main/folder/input.txt'; Arg_out = '/path/to/my/main/folder/file.txt'; matlab_script1\""
baseCmd1 = ['/usr/local/MATLAB/R2018a/bin/matlab', '-nodesktop', '-nosplash', '-nodisplay', 'nojvm', cmd1]
os.chdir('/path/to/matlab_script1')
sudo_cmd = sp.Popen(['echo', pwd], stdout=sp.PIPE)
exec1 = sp.Popen(['sudo', '-S'] + baseCmd1, stdin=sudo_cmd.stdout, stdout=sp.PIPE, stderr=sp.PIPE)
out, err = exec1.communicate()
return out
Any suggestions ?
Finally I managed to find the solution of that issue by myself. The problem came from the kind of user who called the Matlab's script. When I was running the above script from a Python interpreter or from the shell, it was the user (with the user password) who was running the script while when I was calling the script from the client the user was the web server's user: www-data.
So at first to avoid the above warning I gave permissions to www-data user to the /var/www folder with the following command:
sudo chown -R www-data /var/www/
After that, the "Warning" disappeared but the script still didn't run because it was asking for www-data's password internally and taking user's password from pymat_config file.
To solve this, I edited /etc/sudoers file in order for www-data to be able to call Matlab scripts without asking password. So I added the following line:
www-data ALL=(ALL) NOPASSWD: /usr/local/MATLAB/R2018a/bin/matlab
and now it runs like a charm !

Running sudo command via CGI (Python)

I am writing a test suite for a web application using Selenium.
In the course of which I need to test behaviour of the app in case a certain service is running or not.
I wanted to create a cgi call to a Python script turning that service on and off.
I know that the cgi call is in the context of the webserver (Apache) however thought that issuing sudo calls like so:
import subprocess
import os
command = 'sudo -S launchctl unload /Library/LaunchAgents/com.my.daemon.plist'
pwd = 'pwd123'
test1 = subprocess.Popen( command, shell=True, stdin=subprocess.PIPE)
test1.communicate(input=pwd)
test2 = os.system( 'echo %s|%s' % (pwd,command) )
would do the trick, well they don't I get return code 256.
What can I do to have this call be executed w/o touching the context in which Apache runs?
As for security: this will only run on a test machine.
The user that Apache runs as needs to be in the /etc/sudoers file, or belong to the sudo group, which I guess it usually doesn't. You also need to make it not ask for a password, which is configured in /etc/sudoers
For Ubuntu, check these out: https://askubuntu.com/questions/7477/how-can-i-add-a-new-user-as-sudoer-using-the-command-line
https://askubuntu.com/questions/147241/execute-sudo-without-password
It could potentially be a pathing issue..
Have you tried writing out the full path like this:
command = '/usr/bin/sudo -S launchctl unload /Library/LaunchAgents/com.my.daemon.plist'
command should be a list, not a string. Try with:
command = ['sudo', '-S', 'launchctl', 'unload', '/Library/LaunchAgents/com.my.daemon.plist']
Cant run sudo this way -- sudo needs a controlling terminal to run.

Set administrator privileges to subprocess.check_call() in Python

I call two executables from a python script one which needs Administrator privileges and one which does not need them. Is there any way by which I can set the Administrator privilege before executing the executable so that it does not ask me for my password.
My script is as follows
import subprocess
subprocess.check_call(['DoesnotNeedAdminPrivilege.exe'])
subprocess.check_call(['NeedsAdminPrivilege.exe'])
I tried to run this script from cmd by starting the cmd to run as an Adminstrator. Is there any way to pass these admin rights to the second executable so that it works without any problem
I found a nasty workaround
f = open('test.cmd', 'w+')
f.write("execute.exe")
f.close()
os.system("runas /savecred /profile /user:Administrator \"test.cmd\"")
or you can use subprocess
Try this out for entering an administrative password.
import subprocess as sp
sp.check_call(['DoesnotNeedAdminPrivilege.exe'])
prog = sp.Popen(['runas', '/noprofile', '/user:Administrator', 'NeedsAdminPrivilege.exe'],stdin=sp.PIPE)
prog.stdin.write('password')
prog.communicate()
Here are the docs on:
Popen - http://docs.python.org/2/library/subprocess.html#popen-constructor
runas - http://technet.microsoft.com/en-us/library/cc771525.aspx
if this works will depend on the program NeedsAdminPrivilege.

Shutting down computer from a python script in apache

I have a headless Raspberry Pi which I want to have an easy means for my child to power down. I tried the following script in the apache web server:
import os
sss = os.popen('echo password | sudo -S shutdown -hP now')
print sss.read()
But nothing happens.
Then I tried:
from subprocess import Popen, PIPE, STDOUT
p = Popen('echo password | sudo -S shutdown -hP now', shell=True, stdOUT=PIPE, stderr=STDOUT)
print p.stdout.read()
Also, nothing was output and no work appears to have been done.
How can I do a shutdown from a web page?
For security reasons Apache user cannot run sudo command.
Usually this is an almost mandatory rule to save you from attacks but for a Raspberry PI installation you may not have this problem so you can just add Apache user to sudoers (or, better, uso visudo to edit that file).
Something else? Yes you may simply add shutdown permissions to Apache user, follow this tutorial. In short you have to change /etc/sudoers with:
%groupName ALL= NOPASSWD: /sbin/shutdown

Categories

Resources