Menu

Project Gimu

Software research and development

Python Script as Systemd Service

Running a python script on a remote machine can be achieved by using a terminal multiplexer (see GNU screen). Another rather convenient alternative to that would be systemd.

Creating our Service

The following python script acts as a single-threaded server, which does not have much functionality besides receiving and sending back (the same) data.

#!/usr/bin/python3 -u
import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 1337
BUFFER_SIZE = 1024

while True:
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.bind((TCP_IP, TCP_PORT))
   s.listen(1)

   conn, addr = s.accept()
   print('Connection address:', addr)
   while True:
      data = conn.recv(BUFFER_SIZE)
      if not data: break
      print("Data received:", data)
      conn.send(data)
   conn.close()

We save the file under /etc/myserver/server.py and mark it as executable via chmod +x /etc/myserver/server.py.

Keep in mind that our server isn’t multi-threaded, meaning that only one connection can be processed at a given time.

Now we create a separate user, that runs the server script:

$ useradd -r -s /bin/false myserveruser
$ chown -R myserveruser:myserveruser /etc/myserver

We proceed to create a unit file for our service:

[Unit]
Description=My Server
After=syslog.target

[Service]
Type=simple
User=myserveruser
Group=myserveruser
WorkingDirectory=/etc/myserver
ExecStart=/etc/myserver/server.py
SyslogIdentifier=myserver
StandardOutput=syslog
StandardError=syslog
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

And save it under /etc/systemd/system/myserver.service. Note: to tell systemd that we have modified the configuration file(s), use systemctl daemon-reload.

Running via systemd

Now that we have created our custom systemd service, enable and start it:

$ systemctl enable myserver
$ systemctl start myserver

Other useful commands to know:

$ systemctl restart myserver
$ systemctl stop myserver

Logging

Logs can be fetched with journalctl:

$ journalctl -u myserver

Leave a Reply