Run Python script on startup as root - python

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.

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.

Related

Daemonize a Python script on Raspbian Buster

I am working on an RFID-based access control system for which I have a working python script. For some specific details if they matter, the main processing is done on a pi zero w, which is connected by USB to a microcontroller that handles the input from the RFID module and sends it to the pi in string format for simplicity. The pi then compares the string received to a yaml file and a schedule and uses GPIO to switch on or off a door strike using a power supply. The issue I'm running into is that the script stops running after about 30 minutes, and I'm not quite sure why, but I think the ideal solution in any case is to daemonize it, because a cron job is too subject to failure and a daemon seems very appropriate for this use. Does anyone have any suggestions for daemonizing the script such that it will start on boot and restart itself if it detects a failure or that it is no longer running?
As larsks said, you can create systemd service
sudo nano /etc/systemd/system/yourscript.service
This file should be something like this (read the documentation for more information):
[Unit]
Description=My cool script
After=multi-user.target
[Service]
User=root
WorkingDirectory=/path/to/your/script/directory/
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/python3 your_script.py
StandardOutput=append:/var/log/your_script.log
StandardError=append:/var/log/your_script.log
SyslogIdentifier=coolawesomescript
[Install]
WantedBy=multi-user.target
Then enable and start it:
foo#bar:~$ sudo systemctl enable yourscript
foo#bar:~$ sudo systemctl start yourscript
Now your script will automatically restart when it crashes
You can check if your script actually works by typing sudo systemctl status yourscript

How to improve Python script performances when launched from systemd?

I have a Raspberry Pi (there is a Debian-based distro) which needs to keep running a service based on a Python script.
What I have done so far has been to create the .service file added to the /lib/systemd/system/ folder, now it is run automatically at the system boot and it is able to be restarted if any crash occurs, furthermore, a little logging system has been added based on syslog.
The content of the .service file looks like this so far:
[Unit]
Description=My_Service
After=network.target network-online.target
After=local-fs.target
[Service]
Type=simple
Restart=always
ExecStartPre=/bin/mkdir -p /home/user/log
ExecStart=/usr/local/bin/python3 -u /home/user/my_service.py
SyslogIdentifier=My_Service
StandardOutput=syslog
StandardError=syslog
[Install]
WantedBy=multi-user.target
Now I've noticed that the script is slighlty less performant than when it is run by terminal.
Because it is the only one script that the system should keep running, I was trying to set it with the highest priority but I am not sure how to do that.
So far I've added the following lines in the [Service] section but I'm not sure if it is ok or if it could be the best practice.
CPUSchedulingPolicy=rr
CPUSchedulingPriority=99
Nice=-20
The question is: How can I set the maximum priority and maximum usage of the system resources for such service in order to maximise its performances?
I'm also trying to disable other system services which are not useful for my embedded system, such as the bluetooth.service, could this kind of work be a good practice?
-- Edit --
No solutions found yet.
To run python script as service I recommend to use Supervisor.
https://rcwd.dev/long-lived-python-scripts-with-supervisor.html

run a python script on raspberry pi turned on

I am working on raspberry pi 3 about 3 months , I had a problem when I started working with it.
I couldn't find an efficient and safe way to run a python script on raspberry when it turns on(without monitor and mouse and keyboard).At the moment I have added "$sudo run myscript.py &" at /etc/profile but sometimes when I turn it on my script doesn't run until I connect monitor and mouse and keyboard to it and run the script with GUI and after that it works fine (again without mouse and keyboard).
I want to know is there any solution that I will be sure my script will run after I turn raspberry pi on?
Thanks a lot
You will want to setup a service and user sudo service <my_service> [start, stop, restart] to get it working on startup. See here for reference.
The /etc/profile is executed when new shell session in being started, so unless you start at least single shell session your script will not be run. Moreover it will be terminated when session stops, and if you start multiple sessions then the script will also be started for each session, which is probably not what you want.
Depending on your init system you would need to create SysVinit or systemd service. Assuming you use systemd based distro (which is currently default for most Linux distributions) you need to do following:
Step 1: Place your script in location from which it will be executed by service. For example /usr/local/bin/ may be good choice.
Step 2: Create service file. Assuming you want to name it myscript.service, create file at following path /etc/systemd/system/myscript.service with following content:
[Unit]
Description=myscript
[Service]
ExecStart="/usr/bin/python /usr/local/bin/myscript.py"
[Install]
WantedBy=multi-user.target
Step 3: Reload systemd daemon and enable your service:
systemctl daemon-reload
systemctl enable myscript
Now after you restart your system, your service should be automatically started. You can verify that using command systemctl status myscript, which returns service status.

Automatically start a program at Raspbian - Raspberry Pi 3

I'm using a Raspberry Pi 3 with Raspbian distribution.
I've written a script in Python 3 and I would need to start it up automatically just when system boots up, without logging in.
I would recommend using systemd to achieve this. Take for example your python script is called hello.py.
Create a systemd service file at /lib/systemd/system/hello.service:
[Unit]
Description=hello.py service file
After=multi-user.target
[Service]
Type=simple
ExecStart=/usr/bin/python /dir/to/your/hello.py
Restart=always
[Install]
WantedBy=multi-user.target
The full list of commands and functions for the systemd service file can be found here.
Add appropriate permissions to the .service file: sudo chmod 644 /lib/systemd/system/hello.service
Reload the systemd daemon: sudo systemctl daemon-reload
Enable the hello systemd service: sudo systemctl enable hello.service
You can check that your service is running by using the command: sudo systemctl status hello.service and check for any errors using sudo journalctl
Raspberry PI has quite good support. Tasks can be schedualed with usage of "crontab" command.
You can find documentation on: Documentation
Within this documentation you have example for running "python" script on Raspberry Pi reboot.
Hope it helps!

Python Script that was called from bash startup script stops after 20mins of running,

I have a python script that has a While True: in it that I would like to have run on startup on a raspberry pi running Jessie.
So far I have a startup bash script in /etc/init.d called startup.sh which contains
sudo python3 /home/pi/Desktop/Scripts/bluez3.py &
When the raspberry pi starts up, the script does run but after 20 minutes the script seems to stop. I have logging in my script and the time-stamp stops exactly 20 mins in.
I did some reading and I think the best option would be to create the python script as a service on the raspberry pi. However, I have not been able to find a decent tutorial about how to do this (and my lack of python knowledge).
My question is, is there another way to resolve my problem or does anyone know of a good tutorial on how to make the python script into a service.
Thanks!
given the name of your script, I'm guessing it's related to some bluetooth stuff. It's likely that after 20 min, whatever you're checking/needing in your script gets unaccessible and throws an exception or something like that. Like a resource being locked, or a bt device being disconnected or a module being unloaded or unavailable or [insert edge case reason here]…
that being said, in between creating a systemd service, you can first play with supervisorctl which is just an apt install supervisor away.
then if you really want to launch it as a service, you can find plenty of examples in /lib/systemd/system/*.service, like the following:
[Unit]
Description=Your service
Wants=
After=bluetooth.target # I guess you need bluetooth initialised first
[Service]
ExecStart=/usr/bin/python3 /home/pi/Desktop/Scripts/bluez3.py
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=always
[Install]
WantedBy=multi-user.target
which I customized from the sshd.service file 😉

Categories