本文将给出ssh无法登陆一些可能的原因及解决办法,并由此总结ssh的相关知识,以及不同发行版中服务启动方式和命令的区别。
排查解决
1.首先查看22端口是否启动,并看是否是ssh服务所用。
netstat -ntlp|grep 22
如果端口占用,则需要关闭对应的服务,重启ssh服务。也可以采用配置其他端口启动ssh服务。
2.查看ssh服务的启动状态
sudo systemctl status sshd
正常情况会输出类似如下内容:
[root@bogon ~]# systemctl status sshd
● sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
Active: active (running) since 日 2020-02-02 20:47:54 CST; 12h ago
Docs: man:sshd(8)
man:sshd_config(5)
Main PID: 1027 (sshd)
Memory: 3.3M
CGroup: /system.slice/sshd.service
└─1027 /usr/sbin/sshd -D
2月 02 20:47:52 bogon systemd[1]: Starting OpenSSH server daemon...
2月 02 20:47:54 bogon sshd[1027]: Server listening on 0.0.0.0 port 22.
2月 02 20:47:54 bogon sshd[1027]: Server listening on :: port 22.
2月 02 20:47:54 bogon systemd[1]: Started OpenSSH server daemon.
2月 03 09:31:03 bogon sshd[2153]: Accepted password for root from 192.168.43.55 port 62885 ssh2
如果不是active 则进行重启服务。(在centos7及ubuntu16以上,使用systemctl命令,具体见下文总结,centos用sshd,ubuntu用ssh)
start/stop/restart
sudo systemctl start sshd
3.如果找不到ssh,说明未安装ssh服务,需要进行安装,并进行启动
sudo apt-get install openssh-server
or
sudo yum –y install openssh-server openssh-clients
安装后可以设置开机启动:
sudo systemctl enable sshd
4.防火墙
systemctl status firewalld
firewall-cmd --state
systemctl stop firewalld.service
systemctl disable firewalld.service
5.重启网络or重启系统[不失为一种手段]
ubuntu
sudo systemctl restart networking
or for centos
sudo systemctl restart network
关于ssh几点总结:
ssh和sshd的区别
ssh 是你连接远程计算机使用的命令 - the client.
sshd 是 daemon 它的运行保证其他客户端能够连接- the server.
systemctl command
它是在新版本Linux中管理服务的新命令。在支持systemd的系统上,都可以使用。
不同Linux版本启动服务的方式
最新版本的Ubuntu 例如Ubuntu Linux 16.04 or 18.0 可以使用systemctl命令来控制服务。早期的版本,还是用serveice命令。查看系统版本用下面命令:
cat /etc/*release*
下面以启动SSH服务为例:与之对应的命令有start/stop/restart
- Ubuntu Linux: Start OpenSSH Server
输入下面的命令:
$ sudo /etc/init.d/ssh start
OR
$ sudo service ssh start
OR for systemd based Ubuntu Linux 16.04 LTS or above server:
$ sudo systemctl start ssh
- CentOS / RHEL / Fedora / Redhat Linux Restart SSH
输入下面命令:
# /etc/init.d/sshd restart
OR
# service sshd restart
如果使用的系统 RHEL/CentOS/Fedora Linux 带有systemd (e.g. RHEL or CentOS v7/8), enter:
$ sudo systemctl restart sshd
- FreeBSD Restart SSH
# /etc/rc.d/sshd restart`
OR
`$ sudo service sshd restart
- OpenBSD Restart SSH service
# /etc/rc.d/sshd restart`
OR
`$ doas /etc/rc.d/sshd restart
OpenSSH Server 配置
比如修改端口或者禁止root登录。
编辑 /etc/ssh/sshd_config :
sudo vim /etc/ssh/sshd_config
- 禁止root登录:
PermitRootLogin no
- 改变默认端口 For example:
Port 2002
保存后. Restart sshd:
service sshd restart