2团
Published on 2024-09-19 / 10 Visits
0
0

Ubuntu 24.04更新ssh默认22端口失效

1. 前言

近期修改主机的ssh默认登录端口(22),在/etc/ssh/sshd_config文件中一阵操作,具体如下:

Include /etc/ssh/sshd_config.d/*.conf

# 取消端口配置前的#,修改端口号为12345
Port 12345
AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

执行重启命令,结果发现ssh服务还是监听在22端口,具体如下:

屏幕截图 2024-09-19 175152.png

2. 原因

去网上冲浪了一阵,发现原因在于Ubuntu 22.10版本开始,修改了其加载方式。在 Ubuntu 22.10 及更高版本中,SSH 守护进程(sshd)使用基于套接字的激活(socket-based activation)。这意味着sshd不再在系统启动时立即启动并监听端口,而是由systemd管理的套接字来激活。

优点:

  • 资源节约:减少了系统启动时的资源消耗,因为sshd只有在需要时才会启动。

    • 每个实例节省3M内存,在大公司的K8S场景中

  • 快速响应:由于systemd预先监听了端口,sshd可以快速响应连接请求。

As of version 1:9.0p1-1ubuntu1 of openssh-server in Kinetic Kudu (Ubuntu 22.10), OpenSSH in Ubuntu is configured by default to use systemd socket activation. This means that sshd will not be started until an incoming connection request is received. This has been done to reduce the memory consumed by Ubuntu Server instances by default, which is of particular interest with Ubuntu running in VMs or LXD containers: by not running sshd when it is not used, we save at least 3MiB of memory in each instance, representing a savings of roughly 5% on an idle, pristine kinetic container.

但是问题出现了,现在并非sshd监听端口,而是由systemd监听端口,这导致修改sshd端口配置文件无法生效。

3. 解决方案

3.1 守旧

#systemctl disable --now ssh.socket
#systemctl enable --now ssh.service

关停ssh.socket服务,重新启用ssh.service服务即可。

3.2 入乡随俗

#mkdir -p /etc/systemd/system/ssh.socket.d
# cat >/etc/systemd/system/ssh.socket.d/listen.conf <<EOF
[Socket]
ListenStream=
ListenStream=12345
EOF
# sudo systemctl daemon-reload
# sudo systemctl restart ssh.socket


Comment