Run python scripts without password

By | February 6, 2025

I have a python program on my raspberry pi which I want to run without requiring a password. The code I want to run is as follows.

import os

def restart_pi():
    os.system('sudo reboot')

To run the restart_pi() function that requires sudo privileges without prompting for a password, you can configure the sudoers file. Here’s how to do it:

Use the visudo command to edit the sudoers file safely. Open a terminal and type

sudo visudo

Then add a specific rule as follows replacing the username with the one on your pi

username ALL=(ALL) NOPASSWD: /sbin/reboot

Save and exit using Ctrl + X, then Y.

It important to limit this command to just the commands you need. In the case of my code restarting the pi is a pretty safe thing to do.