systemd does not allow ordinary users to start or stop system services. In CentOS/RHEL7, “systemd –user” instances are not started for users therefore user-managed systemd instances are non-functional. But we can use sudo to configure command-sudo rules allowing users and/or groups to trigger certain systemctl commands.
Follow the steps outlined below to configure sudo rules for non-root users to run a specific systemctl command.
1. Use the command “visudo” to configure the sudo rules to allow test user and logusers group to run below commands:
- /usr/bin/systemctl start rsyslog
- /usr/bin/systemctl restart rsyslog
- /usr/bin/systemctl stop rsyslog
# visudo ## Manage specific systemd services Cmnd_Alias SYSTEMD = /usr/bin/journalctl, /usr/bin/systemctl start rsyslog, /usr/bin/systemctl restart rsyslog, /usr/bin/systemctl stop rsyslog ## Allows test user and the logusers group to run init-system commands using the SYSTEMD command alias test ALL = SYSTEMD @logusers ALL = SYSTEMD
Verify the rules are working as expected with and without the sudo command.
Without sudo Command
$ systemctl restart rsyslog Failed to issue method call: Access denied
With sudo command
$ sudo systemctl restart rsyslog echo $? 0
Running a command not specified in sudoers file
$ sudo systemctl restart crond [sudo] password for test: Sorry, user testis not allowed to execute '/bin/systemctl restart crond' as root on geeklab.example.com.
As discussed above, make sure you use the exact syntax in the sudoers file. As seen in the example below “rsyslog.service” and “rsyslog” are actually the same when we use them with systemctl but for the sudoers file they are 2 different commands and will throw an error as shown below:
$ sudo systemctl restart rsyslog.service Sorry, user test is not allowed to execute '/bin/systemctl restart rsyslog.service' as root on geeklab.example.com.
$ sudo systemctl restart rsyslog; echo $? 0