I am writing a bash script to perform a daily backup. This script will ultimately run automatically every morning (cron or systemd).
What I would like to accomplish is
- Stop myservice
- Perform backup procedures
- Start myservice
The bash script I have created looks something like this:
# Stop myservice
systemctl stop myservice.service
# Do all the backing up here...
# Start myservice
systemctl start myservice.service
The issue I am having is that when I run this script, it requires my password during the systemctl stop/start calls. If this is to run automatically, obviously it can't require a password every time. How do I run this script automatically without requiring this password?
Ubuntu 18.04
Thanks!
Best Answer
You have multiple possibilities, depending on your needs and preferences.
An apparent approach …
… would be to run the whole script as user
root
by adding it toroot
'scrontab
(usingsudo crontab -e
). It won't need any password then whensystemctl stop/start myservice.service
is run. The downside is that you may need to run the backup tasks as another user (saynoslenkwah
) and have to switch to that other user for the backup. Example:Another approach …
… would be to add the
systemctl
commands to a file in the/etc/sudoers.d
directory so that a specific user may run them without supplying a password.issue
sudo visudo -f /etc/sudoers.d/noslenkwah
(The filename,noslenkwah
doesn't matter, it is just a personal habit of mine to name the files after the "main" user affected by the settings in that file. It just needs to be a file below the directory/etc/sudoers.d
.)Add the following lines and save the file.
This allows the user
noslenkwah
to runsudo systemctl stop myservice.service
andsudo systemctl start myservice.service
without a password. It defines a socalled command alias (collection of commands) namedMYSERVICE
and then allowsnoslenkwah
ALL
computersroot
MYSERVICE
Replace
noslenkwah
andmyservice
with the actual username and service name. Note that you really must issuesudo systemctl start myservice.service
for this to work (notsudo systemctl start myservice
(without.service
, for example).Don't care about the "on
ALL
computers" part. This is relevant only if you intend to distribute the very samesudoers
file to multiple computers.You would then change your backup script to
and have it run as user
noslenkwah
.