Python в автозагрузку linux

Autostart python scripts on boot with systemd

Recently I tried to run one of my Python projects on boot, and I was faced with the problem on how to do this elegantly on current Debian based Linux distros. After a bit of googling I found a quick and reliable way by utilizing a systemd service. Never mess again with strangle rc.local files or crontab @reboot solutions. With systemd services you can also reliably access logs and see the status of your process. This is especially useful for Python projects on things like a Raspberry Pi which you use headless and want to start your script as soon as it boots.

How To

Replace with a name descriptive of your project. Make it memorable because you probably have to remember it at some point.

    Find out the path to your python runtime with which

sudo systemctl --force --full edit .service 
[Unit] Description= After=network.target [Service] ExecStart= .py [Install] WantedBy=multi-user.target 
sudo systemctl daemon-reload 
sudo systemctl enable .service 

Variations

Time of start

The previous example assumes you want your script to start after the network interfaces were initialized and the OS is ready to use. You can change this behaviour by changing the values of the After= and WantedBy= parameters in the service file.

Читайте также:  Автозагрузка python скриптов linux

Virtual Environments

You can also start python scripts utilizing virtual environments this way by explicitly using the path to the python binary of your virtual environment like this:

ExecStart=/home//venv/bin/python .py 

Changing working directory

You can also change the working directory for your service before you start your script. This is especially useful if you reference relative paths in your code like machine learning models or asset folders. You can do this by adding a WorkingDirectory property to the service. Be aware that you still have to use absolute paths to reference your python executable and your script.

[Service] WorkingDirectory=/home/user/ ExecStart=/home//venv/bin/python .py 

Execute as user or group

Lastly you can execute your python script as specific Linux user and/or group e.g. as user “pi” if there are some specific permissions requiring this. For this to work you specify a user or group in the service part of the file. This is an example on how to do this for the user pi:

[Unit] Description= After=network.target [Service] ExecStart= .py User=pi Group=pi [Install] WantedBy=multi-user.target 

Managing the running script

Stop & Restart

You can stop your service by executing:

sudo systemctl stop .service 

The same goes for restarting it via:

sudo systemctl restart .service 

Status & Basic logs

You can check if your service is running or crashed by typing:

sudo systemctl status .service 

This will also show you the last few lines logged by your script (e.g. print statements).

Disable autostart again

You can disable autostart for your new service at any time by typing:

sudo systemctl disable .service 

© 2023 David and Niklas Merz · Powered by Hugo & Coder.

Источник

Как поставить на автозапуск python скрипт в linux?

Есть запускаю просто из под рута в консоле — всё срабатывает ок. Приложение запускается, всё отрабатывает ок.

Но не понимаю как это поставить на автозапуск (провайдер зачастил ребутать серверы).
Скрипт сервиса:

[Unit] Description=My Script Service After=default.target [Service] Type=simple ExecStart=/root/runserver.sh Restart=always User=root [Install] WantedBy=multi-user.target

5d0bf623e0001703016171.png

Лежит в /lib/systemd/system/runapp.service
Скрин статуса:

Заодно подскажите куда как прописать правила iptables так же при старте 🙂
Что читаю и пытаюсь повторить — не работает :\

POS_troi

1. Вам влом прочитать документацию на инструменты используемые вами
— docs.gunicorn.org/en/stable/deploy.html
2. Вам влом в гугле вбить запрос на поиск методов деплоя используемых вами инструментов
— https://bartsimons.me/gunicorn-as-a-systemd-service/
3. Вам влом изучать операционную систему и её инструменты
— https://habr.com/ru/company/southbridge/blog/255845/
4. Выкиньте нафиг свой скрипт, systemd супервизор и он не занимается запуском скриптиков, а если уж очень хочется то не забывайте про «переменные среды».

Но зато не влом прийти и написать много букав на тостере и при этом даже не удосужились указать операционную систему, конкретную а не общее Linux коих 100500 дистров и у многих свои приколы.

[Unit] Description=My Script Service [Service] WorkingDirectory=/home/dev/myapp ExecStart=source venv/bin/activate && gunicorn -c gunicorn_config.py run_app:app Restart=always RestartSec=30 #перезагрузка сервиса, если вдруг упадет. StandardOutput=syslog StandardError=syslog SyslogIdentifier=my-python-app #Environment=NODE_ENV=production PORT=3080 (это для nodejs, но можете тоже поиграть, если надо). [Install] WantedBy=multi-user.target

Попробуйте разместить в /etc/systemd/

iptables на разных осях по разному. Создаете скрипт типа:

#! /bin/sh iptables -F iptables -X iptables -t nat -F iptables -t nat -X iptables -t mangle -F iptables -t mangle -X iptables -t raw -F iptables -t raw -X iptables -t security -F iptables -t security -X iptables -P INPUT DROP iptables -P OUTPUT ACCEPT iptables -P FORWARD DROP iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

По iptables нашел такое решение https://help.ubuntu.com/community/IptablesHowTo#Tips
+ наверно так же на сервис повешу, спасибо.
У меня VPS ubuntu 16.04

Еще помогло это https://habr.com/ru/post/351566/, у меня фласк, но суть так же
+ там есть очень важный момент — в конфиге гуникорна не должен стоять параметр daemon=True

Войдите, чтобы написать ответ

Какими способами можно организовать смену паролей от учетных записей AD?

Источник

How to Run Python Script at Startup in Ubuntu

The reputation of Python as a programming language speaks for itself. This programming language is attributed as general-purpose, high level, and interpreted.

Most Linux users are in love with the Python programming language due to its code readability which makes it easy to follow and master even for a beginner in the programming world.

Some advantages of Python Programming language are listed below:

  • Open-source and community development support.
  • Rich in third-party modules.
  • User-friendly data structures.
  • Dynamically typed programming language.
  • Interpreted language.
  • Highly efficient.
  • Portable and interactive.
  • Extensive libraries support.

The above-mentioned features make Python ideal for projects related to software development (desktop, web, gaming, scientific, image processing, and graphic design applications), operating systems, database access, prototyping, and language development.

This article will address the use of Python as a scripting language in an operating system environment (Ubuntu).

Prerequisites

Ensure you meet the following requirements:

  • You are a sudoer/root user on a Linux operating system distribution.
  • You can comfortably interact with the Linux command-line environment, interpret, and execute its associated commands.
  • You have the latest version of Python installed on Ubuntu.

Confirm that you have Python installed by running the command:

$ python3 --version Python 3.8.10

Running a Python Script at Startup in Ubuntu

The following steps will help us achieve the main objective of this article.

Step 1: Create Your Python Script

Create your Python script if it does not already exist. For this article guide purpose, we will create and use the following Python script.

Add the following Python script.

from os.path import expanduser import datetime file = open(expanduser("~") + '/Desktop/i_was_created.txt', 'w') file.write("This LinuxShellTips Tutorial Actually worked!\n" + str(datetime.datetime.now())) file.close()

Upon rebooting our Ubuntu system, the above Python script should be able to create a file called i_was_created.txt on the Ubuntu Desktop (Desktop). Inside this file, we should find the text This LinuxShellTips Tutorial Actually worked! together with the date and time of its creation.

Next, move the Python Script to a directory where it can be executed with root user privileges upon system restart. One such viable directory, in this case, is /bin.

Let us move the script using the mv command.

$ sudo mv python_test_code.py /bin

Now create a cron job scheduler that will periodically handle the execution of the above-created Python script (In this case during system startup).

At the bottom of this file, add the line:

@reboot python3 /bin/python_test_code.py &

Save and close the file and then confirm the creation of the cron job schedule:

Check Cron Job in Linux

The @reboot portion of the above line tells the cron job scheduler to execute the script at system startup. The & parameter informs the cron job scheduler to execute the Python script in the background so as not to interfere with normal system startup.

We are now ready to reboot our system

Let us check if our file was created:

$ cat ~/Desktop/i_was_created.txt && echo ''

Run Python Script at Ubuntu Startup

The existence of the above file confirms the Python script was successfully executed at the Ubuntu system startup.

Источник

Auto Start Python Script on Boot (Ubuntu 20.04, Systemd)

NOTE: Use After=network.service if you require network.

Create Bash Script

#!/bin/bash # cd /code/python/myapppython3 /code/python/myapp/run.py >> /code/logs/myapp.log 2>&1

Create Python Script

nano /code/python/myapp/run.py
import signalimport timeimport datetime is_shutdown = False def stop(sig, frame): print(f"SIGTERM at datetime.datetime.now()>") global is_shutdown is_shutdown = True def ignore(sig, frsma): print(f"SIGHUP at datetime.datetime.now()>") signal.signal(signal.SIGTERM, stop)signal.signal(signal.SIGHUP, ignore) print(f"START at datetime.datetime.now()>") while not is_shutdown: print('.', end='', flush=True) time.sleep(1) print(f"END at datetime.datetime.now()>")

Test Systemd

sudo chmod 744 /code/scripts/myapp.shsudo chmod 664 /etc/systemd/system/myapp.service
sudo systemctl daemon-reloadsudo systemctl enable myapp.service
sudo systemctl start myapp.service
sudo systemctl start status.service
sudo systemctl stop myapp.service

Restart server to test if the service started on reboot

Anaconda

Systemd is run as root by default. If you are using Anaconda (or maybe pyenv ), current user might not run the same python version/environment as root.

NOTE: I tried changing the user via Service.User , but it still uses the system default python interpreter

You can find the python interpreter path using which python or python -c «import sys; print(sys.executable)»

which pythonsudo which python

Edit the bash script to use the correct python interpreter

/opt/conda/bin/python3 /code/python/myapp/run.py >> /code/logs/myapp.log 2>&1

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

Travelopy — discover travel places in Malaysia, Singapore, Taiwan, Japan.

Источник

Оцените статью