0

I'm curious about the best way (most secure way) to execute a python program and after it ends shutdown the system (using sudo in a ssh session).

What I would do initially is:

nohup python py_name.py && sudo shutdown -h now & or nohup python py_name.py ; sudo shutdown -h now &

(sudo because I'm in a ssh session and I can't shutdown without it and nohup and & because I want to leave the system after executing)

The problems is that the python program is like 5-8 hour long and I don't want the shell prompt for pw after that (is somehow possible to prompt when executing first command?). My system is ubuntu 18.04 so I guess that "sudoing" both can't work because of the timeout of sudo (15 min?).

One option is to enter superuser mode for both commands or scripting it and executing sudo ./script, but is it secure taking into account that it is executing a python program? (It's an easy home PC setup so maybe it's not a problem)

Is there any other way I'm not aware of?

----- EDIT -----

I tried to run sudo sh -c 'python py_name.py && sudo shutdown -h now'. sudo sh -c 'command' executes another shell to run the command and it could work this way because all the shell is in sudo. The problem is that I use a python environment and this new shell does not come activated with it.

-----SOLUTION-----

The real solution is as said (by solution), changing the sudoers file sudo visudo to add shutdown to the list that does not need password when it runs sudo shutdown. Each sudoers file is different, but in my case, I needed to add my_username ALL=(ALL) NOPASSWD: /sbin/shutdown, where the first "space" is tab, and /sbin/shutdown is the path to the command you want to execute (you can check path with command -v shutdown).

1

you can set for this user passwordless sudo in /etc/sudoers file. e.g. on ssh server (also can be more restrictive of course, i.e. allowing only shutdown to be paswordless etc):

youruser ALL = (ALL) NOPASSWD: ALL

| improve this answer | |
  • oh cool, and you know if running a python script in sudo is secure if done in my home PC (only user) using ssh in local network? – Aurelie Navir May 23 at 16:24
  • @AurelieNavir if it is your own home single user machine, the only problem I see is that you can screw something up with your system by running python ( obviously depends what your python does ) as superuser. But why? use sudo only with shutdown. – Alex P May 23 at 16:29
  • yep, no problem then I guess. Thx – Aurelie Navir May 23 at 16:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.