How do I create a python 3 service that uses socket with systemd?
Here is ready to go simple shell deploy commands for your case, you can change directories, name, description of service or script and so on, description is below:
Make directory and script itself
mkdir /usr/src/python-socket -p
cat > /usr/src/python-socket/python-socket.py << 'EOL'
import socket
host = '127.0.0.1'
port = 9999
BUFFER_SIZE = 1024
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_tcp:
socket_tcp.bind((host, port))
socket_tcp.listen(5) # Esperamos la conexión del cliente
conn, addr = socket_tcp.accept() # Establecemos la conexión con el cliente
with conn:
print('[*] Conexión establecida')
while True:
# Recibimos bytes, convertimos en str
data = conn.recv(BUFFER_SIZE)
# Verificamos que hemos recibido datos
if not data:
break
else:
print('[*] Datos recibidos: {}'.format(data.decode('utf-8')))
conn.send(data) # Hacemos echo convirtiendo de nuevo a bytes
EOL
Set up variables for create systemd service
SERVICE_NAME=python-socket
SERVICE_DESCRIPTION="Test python service"
SERVICE_COMMAND="/usr/bin/python3 /usr/src/python-socket/python-socket.py"
SERVICE_WORK_DIR=/usr/src/python-socket/
SERVICE_USER=root
Deploy systemd service config
cat > /etc/systemd/system/${SERVICE_NAME}.service << EOL
[Unit]
Description=${SERVICE_DESCRIPTION}
After=multi-user.target
[Service]
Environment="FROM=SYSTEMD"
WorkingDirectory=${SERVICE_WORK_DIR}
Type=simple
User=${SERVICE_USER}
ExecStart=${SERVICE_COMMAND}
RemainAfterExit=no
Restart=always
RestartSec=2
StartLimitBurst=999999
StartLimitInterval=0
KillMode=process
[Install]
WantedBy=multi-user.target
EOL
Apply new service, start it and check
systemctl daemon-reload
systemctl enable ${SERVICE_NAME}
systemctl stop ${SERVICE_NAME}
systemctl start ${SERVICE_NAME}
systemctl status ${SERVICE_NAME}
As a result your systemd service config will looks like
[Unit]
Description=Test python service
After=multi-user.target
[Service]
Environment="FROM=SYSTEMD"
WorkingDirectory=/usr/src/python-socket/
Type=simple
User=root
ExecStart=/usr/bin/python3 /usr/src/python-socket/python-socket.py
RemainAfterExit=no
Restart=always
RestartSec=2
StartLimitBurst=999999
StartLimitInterval=0
KillMode=process
[Install]
WantedBy=multi-user.target
Where:
Environment="FROM=SYSTEMD"
- some env variable if you want pass to your python script
Type=simple
- simple systemd service it will work while script is up
RemainAfterExit=no
Restart=always
RestartSec=2
StartLimitBurst=999999
StartLimitInterval=0
These parameters will not allow your script being down in any conditions it will start on fail continiously
KillMode=process
- This is how your script will stop, if you have not special SIG events in your python script it is universal