Running scripts at startup: What's the best way?
This got me thinking: Why not make screen run on startup? My Linode is running Ubuntu 16.04 LTS. When I looked into how to do this, I ran into several options:
* use crontab and add a line with @reboot
add an entry to the file /etc/rc.local
use the command update-rc.d
I'm not sure which to use and what the differences are. Does anyone have any best practices? I also need to have the script run as a user, not as root, in case that affects how to do things.
Thanks in advance for your insights!
3 Replies
I added the following line to /etc/crontab:
@reboot user /home/user/startup.sh
Here's what's in startup.sh:
#!/bin/bash
screen -S irc -d -m irssi
The irssi command can be replaced by whatever you want running in screen. The -d -m flags are key, though. My first try, I left them out, and though /var/log/syslog showed the script execute, no screen was there on startup. Apparently the normal screen command tries to attach the session to a terminal and quits if it can't find one. screen -d -m starts the screen in detached mode, so it doesn't depend on whether it's being run from a terminal.
At this point, everything ran fine, but screen was opening sh terminals instead of bash, because cron is configured to use sh. Rather than mess with cron, I added this to my .screenrc:
shell "/bin/bash"
I can't give you an opinion on the optimal approach, but I can thank you for the explaining how to do this with cron.
Thx.
You can also do this with systemd(1)… Construct your service definition; install it in the right place and then
sudo systemctl daemon-reload
sudo systemctl enable <yourservice>
Thereafter, <yourservice>
will run at system startup.
To test, you can
sudo systemctl start <yourservice>
sudo systemctl stop <yourservice>
sudo systemctl restart <yourservice>
to make sure <yourservice>
starts, stops and restarts gracefully. You should do this before you enable
it.
IMHO, this is the best and most reliable way to do this… YMMV.
-- sw
P.S. To do the opposite, you can
sudo systemctl disable <yourservice>
Here's the systemd(1) service I wrote to re-establish my blacklists into my firewall at system boot:
[Unit]
Description=Install blacklists
After=network.target iptables.service firewalld.service ip6tables.service ipset.
service firehol.service
PartOf=firewalld.service
[Service]
ExecStart=/srv/ids/sbin/iptinstl
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
/srv/ids/sbin/iptinstl
is the script I wrote to install the blacklists. Whenever the content of the blacklists change while the system is running (every 4 hrs), I can install the updated blacklists by
sudo systemctl restart blacklist