SSH is commonly used for tasks such as logging into remote servers and pushing or updating code via Git. While establishing a single SSH connection may not take long, frequently logging into the same server can become tedious and time-consuming. If you log in using a username and password, having to enter your password every time is even more frustrating. Additionally, when using Git, you might need to run git pull and git push often in a short period. If each operation requires re-establishing a connection, the waiting process can be quite annoying.
In fact, SSH has an “lesser-known” feature that allows connection reuse. A new connection is only created during the first login, and subsequent sessions can reuse this existing connection. This makes subsequent logins very fast and eliminates the need for password authentication. The configuration is also simple; here is the code.
Modify the ~/.ssh/config file and add the following configuration:
Host *
ControlMaster auto
ControlPath /tmp/ssh_mux_%h_%p_%r
ControlPersist 600
The meaning is easy to understand:
The line Host * indicates which hosts these configurations and rules apply to. * means it applies to all remote hosts. If you want to specify certain specific hosts, you can use a configuration like Host *.example.com.
ControlMaster auto tells the SSH client to attempt to reuse an existing connection (master connection).
ControlPath specifies the path where the socket for this connection is saved. Here, it is configured in the /tmp directory, but it can actually be any path with read/write permissions. /tmp/ssh_mux_%h_%p_%r configures the socket filename, where %h represents the remote hostname, %p represents the remote SSH server port, and %r represents the remote username for login. These sockets can be deleted at any time (rm). After deletion, the next session will create a new master connection. I once encountered a situation where my local network disconnected, causing several open remote terminals to freeze. Even after the network was restored, they remained stuck, and I couldn’t log in even with new terminals. In this case, simply deleting the previous socket files and logging in again resolves the issue.
ControlPersist is an important option. It indicates that after the session creating the initial connection (master connection) exits, the master connection remains active in the background so that other sessions reusing this connection do not encounter issues. This feature is particularly useful when using Git. When frequently committing and pulling code, each SSH session is very brief. If the master connection stays in the background, subsequent operations will be as smooth as silk.
By adding just these few lines of configuration, the SSH experience improves significantly, making it a must-have for those who prefer convenience.