SSH是Secure Shell的缩写, 是一个应用层的加密网络协议, 它不只可以用于远程登录, 远程命令执行,还可用于数据传输. 当然它由ssh Client和ssh Server端组成, 有很多实现, Ubuntu上就默认安装的OpenSSH, Client端叫做ssh, Server端叫做sshd. OpenSSH只用来做远程登录和命令执行.

## 免密登录

ssh-keygen -t rsa


scp ~/.ssh/id_rsa.pub username@hostname:~/.ssh/authorized_keys
# or


cat id_rsa.pub >> .ssh/authorized_keys


## 保持连接

### 配置服务端

SSH总是被强行中断，导致效率低下，可以在服务端配置，让 server 每隔30秒向 client 发送一个 keep-alive 包来保持连接:

vim /etc/ssh/sshd_config


ClientAliveInterval 30
ClientAliveCountMax 60


sudo service ssh restart


sudo apt-get install openssh-server


### 配置客户端

vim /etc/ssh/ssh_config


ServerAliveInterval 30
ServerAliveCountMax 60


ServerAliveCountMax Sets the number of server alive messages (see below) which may be sent without ssh(1) receiving any messages back from the server. If this threshold is reached while server alive messages are being sent, ssh will disconnect from the server, terminating the session. It is important to note that the use of server alive messages is very different from TCPKeepAlive (below). The server alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The server alive mechanism is valuable when the client or server depend on knowing when a connection has become inactive.

The default value is 3. If, for example, ServerAliveInterval (see below) is set to 15 and ServerAliveCountMax is left at the default, if the server becomes unresponsive, ssh will disconnect after approximately 45 seconds. This option applies to protocol version 2 only; in protocol version 1 there is no mechanism to request a response from the server to the server alive messages, so disconnection is the responsibility of the TCP stack.

ServerAliveInterval Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) will send a message through the encrypted channel to request a response from the server. The default is 0, indicating that these messages will not be sent to the server, or 300 if the BatchMode option is set. This option applies to protocol version 2 only. ProtocolKeepAlives and SetupTimeOut are Debian-specific compatibility aliases for this option.

## 共享SSH连接

ControlMaster auto
ControlPath ~/.ssh/connection-%r@%h:%p


ControlPersist 4h


ForwardAgent yes


Host *
ForwardAgent yes
ServerAliveInterval 3
ServerAliveCountMax 20
TCPKeepAlive no
ControlMaster auto
ControlPath ~/.ssh/connection-%r@%h:%p
ControlPersist 4h
Compression yes