Linux的长连接设置

Linux长连接设置

背景

你可能有以下疑问:

  1. 有时候,会遇到ssh连接到一台远程服务器,但是在一定时间时候之后,会自动断开连接,那么,如何为SSH、vsftpd(Very Secure FTP Daemon)、shell 等延长auto-session超时时间呢?
  2. 针对ssh、ftp、shell和network,有哪些可以配置的session timeout选项呢?
  3. TCP长连接因为莫名其妙原因被断开?

解决方法

影响网络连接session的因素包含三个层面:应用层、TCP层和链路层。以下依次进行相关介绍。

应用层

Bash超时设置

  1. 检查~/.bashrc、/etc/profile或者~/.bash_profile文件中是否存在TMOUT变量;

  2. 可以通过设置TMOUT变量来控制bash的超时时间;

  3. 更多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

参考openssh timeout

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连接已经被破坏,该连接会被断开。

参考资料:TCP keepalive设置

链路层

  1. 防火墙会为每个连接维护一个空闲时间计时器(idle timer);
  2. 如果在指定的时间(idle timeout)内,某个连接上一个包都没发,则防火墙会断开该连接,并将其从connection table删除。(注:tcp的探活包也是包,如果在idle timeout内有探活包发送,则防火墙也会认为该连接是活跃的,并不会关闭该连接);
  3. 默认的idle timeout为60分钟;
  4. 该设置值可以找管理员确认;

下面是防火墙设置的例子:

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值