Ubuntu SSH Port Configuration: Switch Between ssh.service and ssh.socket

Option 1: Restore Traditional ssh.service Mode

This approach is the easiest to understand and is suitable if you previously managed the SSH port through /etc/ssh/sshd_config.

Disable Socket Activation and Enable SSH Service

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

Check Current SSH Port Configuration

grep -n '^Port' /etc/ssh/sshd_config /etc/ssh/sshd_config.d/* 2>/dev/null

If no custom port is configured, add the following line to /etc/ssh/sshd_config:

Port <CUSTOM_PORT>

Restart SSH Service

sudo systemctl restart ssh.service

Verify Listening Port

sudo ss -ltnp | grep <CUSTOM_PORT>

If you see output such as:

*: <CUSTOM_PORT>

or

0.0.0.0:<CUSTOM_PORT>

then the configuration has been applied successfully.


Option 2: Keep ssh.socket and Change the Listening Port

If you prefer Ubuntu’s newer socket-activation approach, modify ssh.socket instead of sshd_config.

Create a Systemd Override

sudo mkdir -p /etc/systemd/system/ssh.socket.d
sudo nano /etc/systemd/system/ssh.socket.d/listen.conf

Add the following content:

[Socket]
ListenStream=
ListenStream=<CUSTOM_PORT>

Reload and Restart

sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
sudo systemctl status ssh.socket
sudo ss -ltnp | grep <CUSTOM_PORT>

Important Note

The following line is critical:

ListenStream=

It clears the default listening port before setting the new one.

Without this line, systemd may continue listening on both the default SSH port and the custom port simultaneously.

留下评论

通过 WordPress.com 设计一个这样的站点
从这里开始