一般情况下,我们连接 vps 或者什么虚拟主机若总是断,可以先查看一下 ssh 配置文件 /etc/ssh/sshd_config ClientAliveInterval ClientAliveCountMax 这两个配置项 是否被注释掉了。默认的这个配置文件里会把这两项给注释掉。如果是被注释掉了,那么请看下面,修改他们让本地的 ssh 服务常驻

一、修改 /etc/ssh/sshd_config

比如 用 vim 修改 使用 / 和 对应的 Pattern 找到下面两行

#ClientAliveInterval 0
#ClientAliveCountMax 3

去掉注释,改成

ClientAliveInterval 30
ClientAliveCountMax 86400

这两个配置项的意思分别是

  1. 客户端每隔多少秒向服务器发送一个心跳数据

  2. 客户端多少秒没有响应,服务器会自动断开连接

二、重启 sshd 服务

# service sshd restart
Redirecting to /bin/systemctl restart sshd.service
# systemctl restart sshd

centOS 7 已经把 sshd 的服务 从 service 管理 迁移到了 systemctl 了。 使用 systemctl 管理即可
比如有以下这些 unit commands

Unit Commands:
  list-units [PATTERN...]         List loaded units
  list-sockets [PATTERN...]       List loaded sockets ordered by address
  list-timers [PATTERN...]        List loaded timers ordered by next elapse
  start NAME...                   Start (activate) one or more units
  stop NAME...                    Stop (deactivate) one or more units
  reload NAME...                  Reload one or more units
  restart NAME...                 Start or restart one or more units
  try-restart NAME...             Restart one or more units if active
  reload-or-restart NAME...       Reload one or more units if possible,
                                  otherwise start or restart
  reload-or-try-restart NAME...   Reload one or more units if possible,
                                  otherwise restart if active
  isolate NAME                    Start one unit and stop all others
  kill NAME...                    Send signal to processes of a unit
  is-active PATTERN...            Check whether units are active
  is-failed PATTERN...            Check whether units are failed
  status [PATTERN...|PID...]      Show runtime status of one or more units
  show [PATTERN...|JOB...]        Show properties of one or more
                                  units/jobs or the manager
  cat PATTERN...                  Show files and drop-ins of one or more units
  set-property NAME ASSIGNMENT... Sets one or more properties of a unit
  help PATTERN...|PID...          Show manual for one or more units
  reset-failed [PATTERN...]       Reset failed state for all, one, or more
                                  units
  list-dependencies [NAME]        Recursively show units which are required
                                  or wanted by this unit or by which this
                                  unit is required or wanted

lsb_release -a 查看一下 当前 系统版本 是 7.6

# lsb_release -a
LSB Version:    :core-4.1-amd64:core-4.1-noarch:cxx-4.1-amd64:cxx-4.1-noarch:desktop-4.1-amd64:desktop-4.1-noarch:languages-4.1-amd64:languages-4.1-noarch:printing-4.1-amd64:printing-4.1-noarch
Distributor ID: CentOS
Description:    CentOS Linux release 7.6.1810 (Core) 
Release:    7.6.1810
Codename:   Core

重启 sshd 服务后 应该就可以解决 ssh 服务总是断的问题了,end.

文章目录