Running a systemd service without sudo privileges

Viewed 1135

I have a PC that transmits log data over a TCP/IP socket to a Raspberry Pi. I have written a python server program that runs on the Pi, so that when certain keywords are encountered, it has to play the corresponding audio track - this is a gist of the problem I'm currently working on.

Now, I want this server program to run as soon as the Raspberry Pi boots up, and so I wrote a systemd service to enable that. Assuming my server code is named as server.py, my service file looks as follows:

[Unit]
Description=Python Server

[Service]
# Command to execute when the service is started
ExecStart=/usr/bin/python3 -u /usr/bin/server.py

[Install]
WantedBy=multi-user.target

I make this server program executable, and I don't face any issues to start and enable the service (verified by rebooting the Pi as well). Now, taking a step back, I play the audio track on the python server program using the following lines (a little snippet):

import subprocess
subprocess.run(["cvlc", "~/Downloads/doors.wav"])

No errors here, all good. But when the service that runs the server program is started, when the specific keyword is encountered, the audio track does not play - it shows an error:

: [00005565470df480] vlcpulse audio output error: PulseAudio server connection failure: Connection refused
: [0000556547157310] dbus interface error: Failed to connect to the D-Bus session daemon: Unable to autolaunch a dbus-daemon without a $D
: [0000556547157310] main interface error: no suitable interface module
: [000055654700c570] main libvlc error: interface "dbus,none" initialization failed
: [0000556547101460] main interface error: no suitable interface module
: [000055654700c570] main libvlc error: interface "globalhotkeys,none" initialization failed
: [0000556547101460] dummy interface: using the dummy interface module...
: [00007f5f98c0b610] idummy demux: command `quit'

This same error shown above occurs when I try to play the audio from the command line with sudo, that is:

cvlc ~/Downloads/doors.wav

which led me to believe that if the service is enabled, then the whole python program corresponding to the service is run with sudo privileges automatically, even if I don't intend that to happen. I did a little bit of digging, but based on what I understand, to run the service, sudo privilege is necessary. I was not able to find a solution to run vlc with sudo, although I understand that ideally sudo privileges should not be given to something such as vlc. Is there a way around this?

1 Answers

This is happening because the PulseAudio server runs under your user, not as root. The service you are starting runs as root and tries to connect to root's PulseAudio server.

You can run specify which user/group to run the service as under the [Service] section with the User and Group directives.

You can also run the service as your user like this:

$ systemctl start --user <service>.service

Related