Wilmer Kluever
Wilmer Kluever

Reputation: 109

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.

Upvotes: 4

Views: 5658

Answers (1)

Aplet123
Aplet123

Reputation: 35560

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.

Upvotes: 9

Related Questions