Add startup script on Ubuntu 20.04

Add service to Ubuntu and run it from startup

$ cat /etc/systemd/system/ssh_tunnel_001.service

[Unit]
Description = Reverse ssh tunnel
After =  network-online.target 
#Requires

[Service]
User = root
Environment=AUTOSSH_GATETIME=0
ExecStart = /usr/bin/autossh -M 0 -q -N -o "PubKeyAuthentication=yes" -o "PasswordAuthentication=no" -o "ExitOnForwardFailure=yes" -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3"  -i /home/[LOCAL USER]/.ssh/id_rsa -R [REMOTE PORT]:localhost:22 -l [REMOTE LOGIN] [REMOTE HOST]
ExecStop= /usr/bin/killall autossh

[Install]
WantedBy = multi-user.target

$ sudo systemctl daemon-reload
$ sudo service ssh_tunnel_001 restart
$ service ssh_tunnel_001 status

Timer trigger

Learn from [2] 

$ cat /etc/systemd/system/pip_report.timer 

[Unit]
Description=Public ip report

[Timer]
OnUnitActiveSec=10s
OnBootSec=10s

[Install]
WantedBy=timers.target


$ sudo systemctl daemon-reload
$ sudo systemctl enable pip_report.timer

Created symlink /etc/systemd/system/timers.target.wants/pip_report.timer → /etc/systemd/system/pip_report.timer.
$ sudo systemctl start pip_report.timer
$ sudo systemctl list-timer --all

Remove timer

$ sudo systemctl stop pip_report.timer
$ sudo systemctl disable pip_report.timer
Removed /etc/systemd/system/timers.target.wants/pip_report.timer.
$ sudo rm /etc/systemd/system/pip_report.timer


Remove the service

$ systemctl stop [servicename]
$ systemctl disable [servicename]
$ rm /etc/systemd/system/[servicename]
$ rm /etc/systemd/system/[servicename] # and symlinks that might be related
$ rm /usr/lib/systemd/system/[servicename] 
$ rm /usr/lib/systemd/system/[servicename] # and symlinks that might be related
$ systemctl daemon-reload
$ systemctl reset-failed

Real life example

[1]

Reference

[1] S. (2024, February 4). Ssh reverse tunnel. https://sfleelfs.blogspot.com/2023/08/ssh-reverse-tunnel.html#startservice

[2] Run script every 30 min with systemd. (n.d.). Unix & Linux Stack Exchange. https://unix.stackexchange.com/a/198450/56400


Comments