Linux长连接设置
背景
你可能有以下疑问:
- 有时候,会遇到ssh连接到一台远程服务器,但是在一定时间时候之后,会自动断开连接,那么,如何为SSH、vsftpd(Very Secure FTP Daemon)、shell 等延长auto-session超时时间呢?
- 针对ssh、ftp、shell和network,有哪些可以配置的session timeout选项呢?
- TCP长连接因为莫名其妙原因被断开?
解决方法
影响网络连接session的因素包含三个层面:应用层、TCP层和链路层。以下依次进行相关介绍。
应用层
Bash超时设置
-
检查
~/.bashrc、/etc/profile
或者~/.bash_profile
文件中是否存在TMOUT
变量; -
可以通过设置
TMOUT
变量来控制bash的超时时间; -
更多
TMOUT
的信息,请参考TMOUT# export | grep TMOUT # Check if bash shell timeout is set or not # echo "TMOUT=9999" >> ~/.bashrc # Change the value
openssh-servers 和 openssh-clients
vsftpd
通过设置以下文件的以下选项为合适值即可:
# vi /etc/vsftpd/vsftpd.conf
# Specifies the maximum amount of time between commands from a remote client. Once triggered, the connection to the remote client is closed. The default value is 300.
idle_session_timeout=0
TCP 层
主要涉及TCP的Keepalive机制。有时候是因为kernel层面的tcp_keepalive相关的配置导致远程session被关闭的,重要的配置参数有以下三个,可以根据场景选择合适的值。
echo 600 > /proc/sys/net/ipv4/tcp_keepalive_time
echo 60 > /proc/sys/net/ipv4/tcp_keepalive_intvl
echo 20 > /proc/sys/net/ipv4/tcp_keepalive_probes
- tcp_keepalive_time:发送探活的时间间隔;
- tcp_keepalive_intvl: 如果第一次探活失败,下个重试探活包发送的时间间隔;
- tcp_keepalive_probes: 探活的重试次数。
以上面的参数为例进行说明,tcp每隔600秒(10分钟),检测一次TCP长连接是否存活,如果第一次检测失败,则隔60秒(1分钟),重新发送下一次探活包,如果发送了20次探活包都失败,则认为这个TCP连接已经被破坏,该连接会被断开。
链路层
- 防火墙会为每个连接维护一个空闲时间计时器(idle timer);
- 如果在指定的时间(idle timeout)内,某个连接上一个包都没发,则防火墙会断开该连接,并将其从connection table删除。(注:tcp的探活包也是包,如果在idle timeout内有探活包发送,则防火墙也会认为该连接是活跃的,并不会关闭该连接);
- 默认的idle timeout为60分钟;
- 该设置值可以找管理员确认;
下面是防火墙设置的例子:
hostname(config-pmap-c)# set connection timeout tcp hh:mm:ss [reset] The tcp hh:mm:ss keyword sets the idle timeout between 0:5:0 and 1193:00:00. The default is 1:0:0. You can also set this value to 0, which means the connection never times out. The reset keyword sends a reset to TCP endpoints when the connection times out. The adaptive security appliance sends the reset packet only in response to a host sending another packet for the timed-out flow (on the same source and destination port). The host then removes the connection from its connection table after receiving the reset packet. The host application can then attempt to establish a new connection using a SYN packet.
参考链接:https://access.redhat.com/solutions/23874