安装OpenSSH后SSH连接localhost遇连接重置问题如何解决?
Let’s work through this issue step by step—this error typically indicates the SSH server isn’t accessible for one of a few common reasons. Here’s what to check:
Verify the SSH server is running
First, make sure thesshdservice is up and running. Run this command to check its status:systemctl status sshd
(If you’re on an older system without systemd, useservice ssh statusinstead.)
If it shows "inactive" or "failed", start the service with:systemctl start sshd
To ensure it starts automatically on boot, run:systemctl enable sshdCheck if port 22 is allowed through the firewall
Your firewall might be blocking incoming connections on port 22.
Forufw(common on Ubuntu/Debian), check the status with:ufw status
If "OpenSSH" isn’t listed as allowed, add the rule:ufw allow ssh
Foriptables, add a rule to allow TCP traffic on port 22:iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Don’t forget to save the iptables rules afterward (tryiptables-save > /etc/iptables/rules.v4on Debian/Ubuntu).Inspect the SSH server configuration
A misconfiguredsshd_configfile can cause connection resets. Open the file with your editor:sudo nano /etc/ssh/sshd_config
Check these key settings:- ListenAddress: Should be set to
0.0.0.0(to listen on all interfaces) or explicitly include127.0.0.1 - PasswordAuthentication: Ensure this is set to
yes(unless you’re using SSH keys and have that configured properly) - PermitRootLogin: If you’re trying to connect as root, make sure this isn’t set to
no(though it’s safer to use a regular user) - AllowUsers: If this line exists, confirm your user is listed here (e.g.,
AllowUsers your_username)
After making changes, restart the SSH server:systemctl restart sshd
- ListenAddress: Should be set to
Check if port 22 is being used by another process
Sometimes another application might be occupying port 22. Use this command to see what’s listening on port 22:ss -tulpn | grep 22
If you see a process other thansshdusing the port, either stop that process or change the SSH port insshd_config(setPortto something like 2222, restart the service, then connect withssh user@localhost -p 2222).Check SELinux (if you’re using it)
SELinux can block SSH connections even if the firewall is open. First, check its status:getenforce
If it returns "Enforcing", try temporarily disabling it to test:setenforce 0
If the connection works after this, you’ll need to update SELinux rules to allow SSH. For example, to ensure port 22 is labeled correctly:semanage port -a -t ssh_port_t -p tcp 22
Then re-enable SELinux withsetenforce 1.Look at SSH server logs for specific errors
The logs will give you detailed info about why the connection is being reset. Run this command to tail the auth logs:tail -f /var/log/auth.log
(On RHEL/CentOS, the log is/var/log/secure.)
Try connecting again while watching the logs—you’ll see exactly what’s failing (e.g., authentication issues, configuration errors).
内容的提问来源于stack exchange,提问作者Shehan Ekanayake

