一键解决SSH登录Linux长时间不操作就会自动断开问题

74 阅读1分钟
  1. 上传脚本

  2. 赋权脚本:chmod +x fix_ssh_keepalive.sh

  3. 执行:sudo ./fix_ssh_keepalive.sh

  4. 执行:source /etc/profile

  5. 执行:unset TMOUT

附:

#!/bin/bash

set -euo pipefail

TS=$(date +%Y%m%d%H%M%S)
echo "时间戳: $TS"
echo "1) 查找系统中设置 TMOUT / autologout 的文件..."
FOUND_FILES=$(grep -R --line-number -E "(^|[^A-Za-z0-9_])(TMOUT|autologout)" /etc /root /home 2>/dev/null | cut -d: -f1 | sort -u)

if [ -n "$FOUND_FILES" ]; then
  echo "发现以下文件包含 TMOUT/autologout(将备份并尝试注释这些行):"
  echo "$FOUND_FILES"
else
  echo "未在 /etc /root /home 下发现显式的 TMOUT/autologout 赋值。"
fi

for f in $FOUND_FILES; do
  if [ -f "$f" ]; then
    echo "备份并处理: $f"
    cp -a "$f" "${f}.bak.$TS"
    # 注释掉常见的 TMOUT/auto 设置行(保留原文作为注释)
    sed -E -i.bak "/TMOUT/ s/^([[:space:]]*)(.*)$/# disabled by fix_disable_auto_logout: \1\2/" "$f" || true
    sed -E -i.bak "/autologout/ s/^([[:space:]]*)(.*)$/# disabled by fix_disable_auto_logout: \1\2/" "$f" || true
  fi
done

echo "2) 在 /etc/profile.d/ 下添加强制禁用脚本(POSIX / csh)..."
# POSIX shells
cat > /etc/profile.d/zz-disable-tmout.sh <<'EOF'

case "$-" in
  *i*)
    unset TMOUT 2>/dev/null || true
    ;;
esac
EOF
chmod 644 /etc/profile.d/zz-disable-tmout.sh

# csh/tcsh
cat > /etc/profile.d/zz-disable-autologout.csh <<'EOF'

if ( $?prompt ) then
  if ( $?autologout ) then
    unset autologout
  endif
endif
EOF
chmod 644 /etc/profile.d/zz-disable-autologout.csh

echo "3) 尝试在常见全局 bash 配置追加 unset(若文件存在且尚未添加)..."
for BF in /etc/bash.bashrc /etc/bashrc /etc/profile; do
  if [ -f "$BF" ]; then
    if ! grep -q "zz-disable-tmout" "$BF" 2>/dev/null; then
      cp -a "$BF" "${BF}.bak.$TS"
      printf "\n# inserted by fix_disable_auto_logout ($TS) - ensure no TMOUT\nunset TMOUT 2>/dev/null || true\n" >> "$BF"
      echo "已在 $BF 追加 unset TMOUT"
    fi
  fi
done

echo "4) 刷新(只影响新登录会话),并显示当前 TMOUT 值建议检查:"
echo "请重新登录以让改动生效,或手动运行: source /etc/profile"

echo
echo "已完成。已创建以下保护脚本:"
ls -l /etc/profile.d/zz-disable-*.sh /etc/profile.d/zz-disable-*.csh 2>/dev/null || true

echo
echo "建议:在当前会话立即运行: unset TMOUT"
echo "如果你在使用 tcsh,请在 tcsh 里运行: unset autologout"