Running python script as root

nathanpjones / python_as_pi.sh

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

#! /usr/bin/env bash
DIR= $( dirname $( readlink -f » $ » ) )
if [ ! -f $DIR /venv/bin/python ] ; then
echo » This script should be located in the project root directory «
echo » and the virtual environment should be created. «
else
# Change python back to run as pi
sudo chown -v pi:pi » $DIR /venv/bin/python «
sudo chmod -v u-s » $DIR /venv/bin/python «
fi

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

#! /usr/bin/env bash
DIR= $( dirname $( readlink -f » $ » ) )
if [ ! -f $DIR /venv/bin/python ] ; then
echo » This script should be located in the project root directory «
echo » and the virtual environment should be created. «
else
# Change python to run as root
sudo chown -v root:root » $DIR /venv/bin/python «
sudo chmod -v u+s » $DIR /venv/bin/python «
fi

Источник

Running python script as root

SUID root scripts were phased out many years ago if you really want to run scripts as root you need to wrap them in an executable, you can see an example on how to do this on my blog: http://scriptsandoneliners.blogspot.com/2015/01/sanitizing-dangerous-yet-useful-commands.html Question: I’m new to Ubuntu and bash scripts, but I just made and added this to my to run it: The problem I’m having is, I want the script to run as if root is running it (because I don’t want to type my sudo password) I found a few places that I should be able to do and and when I run it, it should run as root.

Running python script as root

I have the following script:

#!/usr/bin/env python import sys import pyttsx def main(): print 'running speech-text.py. ' engine = pyttsx.init() str = "Hi. " if ****(sys.argv) > 1: str = sys.argv[1] engine.say(str) engine.runAndWait() if __name__ == '__main__': main() 

and I have placed it in /usr/bin/speech-test.py

I have also given it executable permissions and ownership to root:

sudo chown root:root /usr/bin/speech-test.py sudo chmod 4755 /usr/bin/speech-test.py 

However, this script will only run correctly if I run as sudo speec-test.py . If I try to run it as just speech-test.py it complains about not finding a bunch of ALSA lib files.

Am I missing something to have my script run with root privileges?

So you want the script to run as root , even without sudo ? For that you would need to set the setuid bit on the script with sudo chmod u+s program . However, most Unix distributions allow this only for binaries, and not for scripts, for security reasons. In general it’s really not a good idea to do that.

If you want to run this script as root, you will have to run as sudo . Or, you have to create a binary that runs your script, so that you can set the setuid bit on this binary wrapper. This related question explains more.

Читайте также:  Использование потоков в python

It’s also a good idea to check the effective uid, and if it’s not root then stop running. For that, add this near the top (thanks @efirvida for the tip!)

if not os.geteuid() == 0: sys.exit("\nOnly root can run this script\n") 

ORIGINAL ANSWER

Maybe your user and root use a different version of python, with different python path , and different set of libraries.

command -v python sudo command -v python 

If the two commands don’t give the same result then you either need to change the setup of the users to use the same version of python (the one that has the ALSA libs), or hardcode the python version the first line of the script.

Also try adding a print sys.path line in the script, and run with your user and with sudo and compare. Probably you’ll get different results. You may need to tweak the PYTHONPATH variable of your user.

It shouldn’t be necessary to make the owner of the script root , and to run it with sudo . You just need to configure python and PYTHONPATH correctly.

I’m not really sure if this is a great method. I tried it and it works fine on arch linux. Let me what you think. If you write a script to execute the .py as different system group, that group can own a python interpreter and have specified root capabilities.

mkdir roottest && cd roottest sudo cp /usr/bin/python ./ sudo groupadd -r rootpython sudo usermod -a -G rootpython newgrp rootpython sudo chown root:rootpython python sudo chmod 750 $bin #that way a normal user can't rwx the python interpreter and the rootpython group cant write. sudo setcap ./python #now the group has specify caps allowing it to act like root sudo getcap ./python sudo sh touch rootfile && echo "original text" > rootfile 

open a new prompt as regular user

newgroup rootpython cd roottest && ./python >> open('rootfile', 'w').write("different text") sudo cat rootfile 

This method is way more secure than sudo if used properly because python can only do what you let it and does not have complete control of the system. The downside is having to either make a copy of the interpreter or to not allow the regular user’s group to use it. DO NOT run all your python code like this, its a big vulnerability if not needed. The cap_net_admin+ep will allow you to change the kernal var ip_forward and for the example above you need cap_dac_override+ep. You can also create a newuser that belongs to the rootpython group, that way you can’t just newgrp rootpython without entering the newuser’s password.

Idk but replacing #!/usr/bin/env python by #!/bin/python worked for me.

Its running privilege is the same as the one who ran it. So if you ran it as yourself, it won’t have su privilege. You have to do it sudo .

Unix — run script as root bash, Remove that root from the */1 * * * * root /home/area/reboot.sh line . Why is it even there? cron runs as root, so all script will be run as root. Also …

Читайте также:  Диалоговое и модальное окно

How to make a script run commands as root

I’m new to Ubuntu and bash script s, but I just made runUpdates.sh and added this to my .profile to run it:

if [ -f "$HOME/bin/runUpdates.sh" ]; then . "$HOME/bin/runUpdates.sh" fi 

The problem I’m having is, I want the script to run as if root is running it (because I don’t want to type my sudo password )

I found a few places that I should be able to do sudo chown root.root and sudo chmod 4755 and when I run it, it should run as root. But it’s not.

The script looks good to me. What am I missing? -rwxr-xr-x 1 root root 851 Mar 23 21:14 runUpdates.sh*

Can you please help me run the commands in this script as root? I don’t really want to change the sudors file, I really just want to run the commands in this script at root (if possible).

#!/bin/sh echo "user is $" #check for updates update=`cat /var/lib/update-notifier/updates-available | head -c 2 | tail -c 1`; if [ "$update" = "0" ]; then echo -e "No updates found.\n"; else read -p "Do you wish to install updates? [yN] " yn if [ "$yn" != "y" ] && [ "$yn" != "Y" ]; then echo -e 'No\n'; else echo "Please wait. "; echo `sudo apt-get update`; echo `sudo apt-get upgrade`; echo `sudo apt-get dist-upgrade`; echo -e "Done!\n"; fi fi #check for restart restartFile=`/usr/lib/update-notifier/update-motd-reboot-required`; if [ ! -z "$restartFile" ]; then echo "$restartFile"; read -p "Do you wish to REBOOT? [yN] " yn if [ "$yn" != "y" ] && [ "$yn" != "Y" ]; then echo -e 'No\n'; else echo `sudo shutdown -r now`; fi fi 

I added the user is to debug, it always outputs my user not root, and prompts for the sudo password (since I’m calling the commands with sudo) or tells me are you root? (if I remove sudo)

Also, is there a way to output the update commands stdout in real time , not just one block when they finish?

(I also tried with the shebang as #!/bin/bash )

setuid does not work on shell scripts for security reasons. If you want to run a script as root without a password, you can edit /etc/sudoers to allow it to be run with sudo without a password.

To «update in real time», you would run the command directly instead of using echo.

Its not safe to do, you should probably use sudoers but if you really need/want to, you can do it with something like this:

echo | sudo -S echo -n 2>/dev/random 1>/dev/random sudo

This works because sudo doesn’t require a password for a brief window after successfully being used.

SUID root scripts were phased out many years ago if you really want to run scripts as root you need to wrap them in an executable, you can see an example on how to do this on my blog: http://scriptsandoneliners.blogspot.com/2015/01/sanitizing-dangerous-yet-useful-commands.html

The example is how to change executable permissions and place a filter around other executables using a shell script but the concept of wrapping a shell script works for SUID as well, the resulting executable file from the shell script can be made SUID.

Python — Django Apache, This is executed within my models.py. command = ‘echo «python /path/to/script.py params» | /usr/bin/at -t [time] &> path/to/at.log’ status = …

Читайте также:  Редактор javascript visual studio

Run script as root bash

I have the below bash script that I’m trying to schedule as a cron job. I have it in /etc/cron.d/cronjob

*/1 * * * * root /home/area/reboot.sh 

But it’s not working. if I run the script from the command line using

#!/bin/bash if [[ `awk '' /proc/uptime | cut -d . -f1` -gt 10 ]];then echo 1 > /proc/sys/kernel/sysrq echo b > /proc/sysrq-trigger fi 

Just use sudo crontab -e to edit the crontab

*/1 * * * * root /home/area/reboot.sh 

Set path at the beginning of your script:

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin 

At this task there are some misleading infos.

First, for the system cron tables (/etc/crontab, /etc/cron.d/*) a username is needed. The job is executed under the environment or that user. This is a difference to the usual user-crontab. So This is correct:

*/1 * * * * root /home/area/reboot.sh ^^^^ username 

About */1 : It means: Every minute, that can be divided by 1 without remainder. So it is the same as * .

An answer to your question: I have no idea, what is going wrong. Setup of PATH= or SHELL= may be a solution, or not. Anyway, setup MAILTO= and cron will send you a mail on errors. Read man 5 crontab . If it is not available at your system, google it.

Make sure you have execute permission for the cron file.

Also try adding the sh in front of the script. So in crontab -e

Linux — how to run command in bash as root?, 0. Use sudo, you can write rules in /etc/sudoers file,for example something like: # format: user host = (run as) NOPASSWD: path developer …

Run entire bash script as root or use sudo on the commands that need it?

I’m working on some installation script in bash (on a Raspberry Pi running Stretch). It will copy files to /usr/local/bin and to my user profile and it will install a few packages if needed. The script is almost 2000 lines and 20–30 commands need root.

Now my question is: should I run the entire script with sudo or just as standard user and sudo only the commands inside the script that need admin rights?

If you know for sure that running the script with sudo won’t do you any harm (For example, it won’t create new files that will now need root privileges, but wouldn’t otherwise), you should run it with sudo .

If you know there are some side effects or you are unsure, do it the safe way and use sudo just where you must.

At the header of script put this:

#!/bin/bash #Detects if script are not running as root. if [ "$UID" != "0" ]; then #$0 is the script itself (or the command used to call it). #$* parameters. if whereis sudo &>/dev/null; then echo "Please type the sudo password for the user $USER" sudo $0 $* exit else echo "Sudo not found. You will need to run this script as root." exit fi fi 

I am getting an error that I should not run script as root, Look, you are signed in as the root user: root@levono. Type sudo su YOURUSERNAME it will be changed to. YOURUSERNAME@levono. then …

Источник

Оцените статью