StephenChan's Tech Space 潜心修炼

27Mar/102

ssh的使用

主要记录一下地址缩写和保持长连接,具体的使用和配置参数可以"man ssh"、"man ssh_config"了解得到。

服务器地址缩写

要登陆一台地址为endlesscode.com,用户名为stephenchan,连接的端口为9527的服务器,需运行以下命令:

ssh stephenchan@endlesscode.com -p 9527

每次都要打这么长的一句命令是件麻烦的事,不过ssh提供地址缩写的功能,可以直接"ssh myserver"就可以了,只要在ssh的配置文件(~/.ssh/config)中,添加以下内容:

Host myserver                          #缩写的地址,在命令行中使用ssh myserver登陆
HostName 192.168.23.202      #服务器的地址
Port 32200                              #ssh的端口
User stephenchan                    #use name
Protocol 2                                #协议版本,可选
ForwardAgent yes                    #自动调用登陆管理器,可选
Compression yes                      #压缩传输,可选

以上的配置是针对一个服务器登陆的配置,也可以在配置文件中以同样的形式配置多台服务器,彼此间不冲突。

保持长连接

默认的ssh不会保持长会话连接,也就是会话过了一段时间后可能会自动断开连接,网上很多文章都说在ssh server端配置成为长连接,但实际上在ssh client端也可以做到。

在上面的ssh的配置文件中增加ServerAliveInterval参数,可以通过man ssh_config找到这个参数的相关说明:

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 compatibil‐ity aliases for this option.

还有一个相关的参数是: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.
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.

结合两个参数设置如下:

Host myserver                          #缩写的地址,在命令行中使用ssh myserver登陆
HostName 192.168.23.202      #服务器的地址
Port 32200                              #ssh的端口
User stephenchan                    #use name
Protocol 2                                #协议版本,可选
ForwardAgent yes                    #自动调用登陆管理器,可选
Compression yes                      #压缩传输,可选
ServerAliveCountMax 20
ServerAliveInterval 240

这些配置参数,使用sftp和scp等命令也是有效的,比如:sftp myserver就可以登陆到myserver的ftp上了。

Filed under: Tools Leave a comment
Comments (2) Trackbacks (0)
  1. add alias:
    ghm=’ssh stephenchan@endlesscode.com -p 9527′
    then you can just type ghm to go to host monster. ^_^

  2. yeah, alias is an alternative solution for url abbreviation. ^_^


Leave a comment


No trackbacks yet.