Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Python script on startup as root

I wrote a python program that I want to execute on boot, but it HAS to be executed as root, and I don't know how. What are the things I need to do to achieve this? Where should I put the file(the script is in a folder with the necessary python packages) so it runs on boot? How do I run the file as root? Whether it is to put the python folder in a certain directory, use another script to execute the python script, or another way, please share your solutions! I'm doing it on a Raspberry Pi, so the OS is Linux.

like image 353
Wilmer Kluever Avatar asked Oct 20 '25 15:10

Wilmer Kluever


1 Answers

The easiest way is to create a systemd service that might look like:

[Unit]
Description=Some python script
After=network.target

[Service]
ExecStart=/usr/bin/python3 script.py
WorkingDirectory=/path/to/scriptdir
StandardOutput=inherit
StandardError=inherit
Restart=always
User=root

[Install]
WantedBy=multi-user.target

You should save this in /etc/systemd/system/servicename.service where servicename can be anything, then set it to run on startup with sudo systemctl enable servicename.service.

like image 70
Aplet123 Avatar answered Oct 22 '25 04:10

Aplet123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!