- Saved searches
- Use saved searches to filter your results more quickly
- License
- Nivratti/python-systemd
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- How to stop and start a systemd service via python script w/o requiring sudo password
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Tutorial to run Python script via systemd
License
Nivratti/python-systemd
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Tutorial to run Python script via systemd
Systemd Service file location and management
- Write Service file
- place your service files inside /etc/systemd/system/ folder
- reload services using systemctl daemon-reload
- after that you are able to perform operations such as
- systemctl start name.service
- systemctl status name.service
- systemctl stop name.service
- systemctl restart name.service
[Unit] # service description Description=**Enter Service Description** After=syslog.target [Service] Type=simple # user and group -- to run service User=**Enter username** Group=**Enter groupname** # project working directory WorkingDirectory=/path/to/working/dir/ # Command to execute when the service is started ExecStart=/usr/bin/python /path/to/python/demo_script.py # Automatically restart the service if it crashes Restart=on-failure # set Python's buffering of STDOUT and STDERR value to systemd, so that output from the # service shows up immediately in systemd's logs StandardOutput=syslog StandardError=syslog [Install] # Tell systemd to automatically start this service when the system boots # (assuming the service is enabled) WantedBy=multi-user.target
[Unit] # service description Description=Python Demo After=syslog.target [Service] Type=simple # user and group -- to run service User=nivratti Group=nivratti # project working directory WorkingDirectory=/programming/python/projects/ # Command to execute when the service is started ExecStart=/usr/bin/python /programming/python/projects/python-demo.py # Automatically restart the service if it crashes Restart=on-failure # set Python's buffering of STDOUT and STDERR value to systemd, so that output from the # service shows up immediately in systemd's logs StandardOutput=syslog StandardError=syslog [Install] # Tell systemd to automatically start this service when the system boots # (assuming the service is enabled) WantedBy=multi-user.target
Imp — Specify python interpreter
Specify Python interpreter
ExecStart=/usr/bin/python /file/path/python_demo_script.py
Service file configuration details
How to stop and start a systemd service via python script w/o requiring sudo password
The following script allows me to check whether a systemd service is active, and to stop or start the service. When executing .stop() or .start() , how can I proceed to stopping and starting the service directly w/o having to supply the sudo password? An example application of where this is useful is stopping and restarting the NetworkManager service.
#!/bin/python3 import subprocess import sys class SystemdService(object): '''A systemd service object with methods to check it's activity, and to stop() and start() it.''' def __init__(self, service): self.service = service def is_active(self): """Return True if systemd service is running""" try: cmd = '/bin/systemctl status <>.service'.format(self.service) completed = subprocess.run( cmd, shell=True, check=True, stdout=subprocess.PIPE ) except subprocess.CalledProcessError as err: print( 'ERROR:', err ) else: for line in completed.stdout.decode('utf-8').splitlines(): if 'Active:' in line: if '(running)' in line: print('True') return True return False def stop(self): ''' Stop systemd service.''' try: cmd = '/bin/systemctl stop <>.service'.format(self.service) completed = subprocess.run( cmd, shell=True, check=True, stdout=subprocess.PIPE ) except subprocess.CalledProcessError as err: print( 'ERROR:', err ) def start(self): ''' Start systemd service.''' try: cmd = '/bin/systemctl start <>.service'.format(self.service) completed = subprocess.run( cmd, shell=True, check=True, stdout=subprocess.PIPE ) except subprocess.CalledProcessError as err: print( 'ERROR:', err ) if __name__ == '__main__': monitor = SystemdService(sys.argv[1]) monitor.is_active()