服务器免密登录

生成密钥

本地客户端生成公私钥 ssh-keygen

客户端配置

~/.ssh vim config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# config文件配置
# 多主机配置
Host name1-p
HostName 服务器主机公网IP地址
Port 默认22端口

Host nam2-p
HostName 服务器主机公网IP地址
Port 6666

Host nam3-p
HostName 服务器主机公网IP地址
Port 22

Host *-p
User root
IdentityFile /Users/liu/.ssh/key_ssh
Protocol 2
Compression yes
ServerAliveInterval 60
ServerAliveCountMax 20
LogLevel INFO

服务端配置

  1. 修改配置

vim /etc/ssh/sshd_config

1
2
3
4
5
6
7
8
9
HostKey /etc/ssh/ssh_host_rsa_key
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys  #公钥文件存储位置
UsePAM no   # CentOS 7.5 中需要修改为 yes

#下面参数选项根据自身需要进行修改;
PasswordAuthentication yes #允许密码认证登录(不要手贱设置为 no, 不然你就登不上服务器了)
PermitRootLogin no      #允许root认证登录
  1. 添加密钥

将客户端id_rsa.pub文件内容复制到服务端authorized_keys文件

  1. 重启服务

重启sshd服务system restart sshd

  1. 登录成功
1
2
3
~ ssh 91-p
Last login: Fri Nov 29 10:16:33 2019 from 172.16.18.131
[root@localhost ~]#

常见问题

  • 查看安全登录日志

cat /var/log/secure

  • 权限问题
1
2
3
chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys # 信任文件的权限,必须是644
chmod 600 ~/.ssh/id_rsa     # 私钥文件的权限
  • 服务器配置问题

getenforce setenforce 0把SELinux关闭