SshAlwaysScreen

This one is for the sysadmins out there. If you use this, you will never have to worry about losing long-running commands when you get disconnected from a remote server.

tl;dr: you should be automatically starting screen when you ssh to remote hosts. This has saved my butt many times. My script below either forces a reconnect to an existing screen session, or starts a new session if one doesn't already exist.

You could substitute tmux if you want, I just don't know the equivalent of screen's -D -RR functionality.

One small annoyance is you get double logins for login failures not related to screen. Oh wel.

Anyway, here's my frankly not very good shell function. Stick it in your .bashrc:

# always use screen on remote hosts if possible
ssh ()
{
    if [ x$1 = x ]
    then
        # ssh doesn't make sense without arguments
        echo "must supply hostname" >%2
    elif [ x"$2" = "x" ]
    then
        # only hostname specified, try to ssh and launch screen
        if ! /usr/bin/ssh -t $1 screen -A -D -RR
        then
            # if attempt to launch screen failed, fall back to regular
            # ssh
            /usr/bin/ssh $@
        fi
    else
        # if user passes more than one arg, it's something to execute
        # on remote host, and thus we don't want to launch remote
        # screen.
        /usr/bin/ssh $@
    fi
}

Anyway, like I said, this will always try to reconnect to an existing screen session, or start a new one if there isn't one on the remote host.

I also recommend that if you run screen on your local machine too, you bind your screen prefix to ctrl-B instead of the default of ctrl-A. Then ctrl-A will always affect the remote session, not your local session. I know it sounds a little complicated, but you get used to it pretty quick. If you need to send a ctrl-A through to the remote server (for example, to go to the beginning of the line), hit ctrl-A A.

If you often log on to random servers, give this a try. You won't regret it.


CategoryGeekStuff
CategoryLinuxStuff



Our Founder
ToolboxClick to hide/show