linuxautossh

about auto ssh in startup script


i want to start up autossh just after the system fire up, so i asked chatgpt; he told me to write a startup script and manage this script with systemctl.

however, things go bad, when i fellowed the instructs, i get an error:

Aug 07 23:35:00 ubuntu autossh[840]: ssh exited prematurely with status 255; autossh exiting

there is my startup script:

#!/bin/zsh                                                                                                                                                                                                    

# tmux for clash
tmux new -d -s clash '/root/clash/clash -d /root/clash'

# tmux for reverse tunnel
tmux new -d -s ssh-tunnel 'autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -N -R 22222:localhost:22 ucloud'

i use autossh to open a reverse tunnel to a remote server; by the way, clash has started successfully

i have tried to start autossh with delay (just 10 s, i guess 10 seconds are enough for the system to prepare itself), that works, but that makes the script ugly.

i want to know, can i fix this without this ambiguous delay


Solution

  • ssh connections need network well prepared, so i try to add an order in my self-defined service

    [Unit]
    Description=Startup Script
    # this After ensures my self-defined service will start after network and ssh are prepared
    After=network-online.target ssh.service
    
    [Service]
    Type=simple
    ExecStart=/usr/local/bin/startup_script.sh
    RemainAfterExit=yes
    
    [Install]
    WantedBy=multi-user.target
    

    that works, goodbye stupid delay