ssh 登录报错 packet_write_wait: Connection to x.x.x.x port 22: Broken pipe

6.48K 浏览开发笔记

ssh 登录报错 packet_write_wait: Connection to x.x.x.x port 22: Broken pipe

问题现象

用 ssh 命令连接服务器之后,如果一段时间不操作,再次进入 Terminal 时会有一段时间没有响应,然后就出现错误提示:

1 packet_write_wait: Connection to x.x.x.x port 22: Broken pipe

只能重新用 ssh 命令进行连接。

解决方法

方法一:如果您有多台服务器,不想在每台服务器上设置,只需在客户端的 ~/.ssh/ 文件夹中添加 config 文件,并添加下面的配置:

1 ServerAliveInterval 60

 

方法二:如果您有多台个人管理服务器,不想在每个客户端进行设置,只需在服务器的 /etc/ssh/sshd_config 中添加如下的配置:

1 ClientAliveInterval 60

 

方法三:如果您只想让当前的 ssh 保持连接,可以使用以下的命令:

1 ssh -o ServerAliveInterval=60 [email protected]

 

在使用SSH管理服务器的时候,如果你很长一段时间不登录,那么很可能等待着你的就是

“Write failed: Broken pipe”

造成这个错误的原因是SSH空闲链接时间太长导致的,所以,我们需要修改SSH默认配置来让它自动关闭链接。

在SSH的配置当中,有两个命令可以实现这个功能,它们分别是

01 //ServerAliveInterval
02          Sets a timeout interval in seconds after which if no data has
03          been received from the server, ssh(1) will send a message through
04          the encrypted channel to request a response from the server.  The
05          default is 0, indicating that these messages will not be sent to
06          the server.  This option applies to protocol version 2 only.
07   
08  //ClientAliveInterval
09          Sets a timeout interval in seconds after which if no data has
10          been received from the client, sshd(8) will send a message
11          through the encrypted channel to request a response from the
12          client.  The default is 0, indicating that these messages will
13          not be sent to the client.  This option applies to protocol
14          version 2 only.

这两个命令前者应用在客户机上,后者应用在服务器上,如果你没有管理员权限,那么前者是很好的选择。
这两个的功能是相同的,都是开启一个发送keep-alive包的功能,这样会允许客户端/服务器在一定时间内发送一个特定的包给对方,一旦超时,则说明断线,就关闭链接。这样就避免了链接长时间挂着导致报错。而且,一旦再次报错,稍等片刻便可以再次登录啦。

总之,二者选择其一即可。

我们先来说服务器端的修改:

1 //编辑文件:
2 /etc/ssh/sshd_config
3 //在内容末尾添加如下语句:
4 ClientAliveInterval 60
5 //保存后重启服务:
6 /etc/init.d/ssh restart

这样,当服务器连续60秒没有接收到来自客户端的keep-alive包,就会关闭会话连接了。

接下来是客户端的修改办法:

如果你没有服务器权限,那么这是个不错的选择——而且,这种办法还有个进阶的使用方法——针对某个服务器单独设置idle时长:

1 //编辑文件:
2  ~/.ssh/config
3 //在里边添加如下语句:
4 ServerAliveInterval 60
5 //针对某一服务器的写法:
6 //使用如下选项连接服务器:
7 ssh -o ServerAliveInterval=60 [email protected]

 

国外的童鞋是这样做的:

Solution:

On the host, add those lines in the file ~/.ssh/config in your home directory

1 Host *
2     ServerAliveInterval 300
3     ServerAliveCountMax 5

http://justcode.ikeepstudying.com/2018/11/ssh-%E7%99%BB%E5%BD%95%E6%8A%A5%E9%94%99-packet_write_wait-connection-to-x-x-x-x-port-22-broken-pipe/

0