简体   繁体   中英

How to run Python script without asking password?

I'm trying to power on my system whenever I require. So I'm using the below commands, which run successfully. But when I run the code, it asks for my password and I have to supply the password manually every time.

os.system('sudo sh -c "echo 0 > /sys/class/rtc/rtc0/wakealarm"' % locals())     
os.system('sudo sh -c "echo %(turnontime)s > /sys/class/rtc/rtc0/wakealarm"' % locals())    

How can I run this code without it asking for my password?

Having your root password in a script file is just plain stupid. Don't do it , there are better alternatives. This page describes how to make a shell script with the setuid bit set, and how to circumvent the restriction most modern Linux distributions have on setuid on shell scripts.

I'll summarize the salient parts here to comply with stackoverflow guidelines. First make a .c file (let's say it's called runscript.c ) with this contents:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
   setuid( 0 );
   system( "/path/to/script.sh" ); 

   return 0;
}

Install gcc ( apt-get install gcc on debian based distro's), then type

gcc -o runscript runscript.c

Now, as root, type

chown root:root runscript script.sh
chmod 4755 runscript script.sh

Now any user should be able to run runscript , and it will execute script.sh as if the user was root.

As long as both files are owned by root and not writeable by anyone else than root, this is fairly secure, and much more secure than embedding the root password in plaintext in a script file.

I've not succeeded in making this work for a script.py file for some reason, so if you really want to run a python script, have the script.sh file run it indirectly. If you do this, remember to set owner and permissions for the python script as well, using chown and chmod as above.

sudo when run with a -S option will read the password from the stdin.

In that case you could use it in a script like:

#!/bin/bash
echo my_awesome_password | sudo -S python awesome_script.py

As @david correctly says, why are you using python to just execute system calls? You could probably have this same script doing the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM