0

I use the contromaster option with my SSH command, like so:

ssh -i id_rsa -o ControlMaster=auto -o ControlPath='~/.ssh/controlmasters/%r@%h' -o ControlPersist=3600 user@hostname

This allows me to reuse my previous connection and log in faster. I have noticed that when I lose my connection WiFi and try to reconnect 10 minutes later, I can no longer reuse the same socket file.

Is there a programmatic way for me to check if the socket file is still alive? Ultimately I would like to create an if statement, that checks wether the existing socket file can be used, proceeds if so, creates a new one if not.

1
  • Perhaps -O check will do this?
    – meuh
    Dec 19, 2023 at 17:01

1 Answer 1

0

Use ssh's -O check command:

$ ssh -O check user@hostname || ssh -Nf user@hostname

On a related note, you can simplify your ssh command by moving various settings into a stanza in ~/.ssh/config. Here I add :%p to your ControlPath pattern, which makes the ssh port number part of the socket file name.

host user@hostname
    IdentitiesOnly yes
    ControlPath ~/.ssh/controlmasters/%r@%h:%p
    ControlMaster auto
    ControlPersist 3600

Then your command becomes simply

ssh -i id_rsa user@hostname

If you always use the same identity file, you can specify it too in ~/.ssh/config, using the parameter IdentityFile. Note that in Ubuntu 22.04 id_rsa is the first entry in the default list that's tried, so you may be able to simply remove that from your command line. See the ssh_config(5) manpage for details.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .