配置远程ssh免密登录
环境
- window10
- Centos7.9
- VScode1.64
背景
同一个window远程连接linux开发环境,远程环境分别在同一个服务器的两个用户下。window上安装的有git,生成密匙和公钥使用git bash。
1.生成密匙和公钥
切到C:\Users\Administrator\.ssh目录下,如果是其他用户就将Administrator替换成你的用户名,鼠标右键选择Git Bash Here打开git bash,执行命令ssh-keygen,一路回车。
$ ssh-keygen # 执行此命令
# 以下为输出
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in test
Your public key has been saved in test.pub
The key fingerprint is:
SHA256:t9ln5ly4SZMXEfA4al4Q9AM+9qnFCAEW9MY2zQRArYE Administrator@DESKTOP-SFKSJF54
The key's randomart image is:
+---[RSA 3072]----+
| +B=oo= ... |
| E..o.* + o .|
| oB B = o |
| .o + B + .|
| S .+ * . |
| .o++ o.|
| oo. O o|
| B * |
| = |
+----[SHA256]-----+
2.将生成的公钥导入到远程主机
ssh-copy-id此命令会将id_rsa.pub的输出导入到远程主机的/home/root/.ssh/authorized_keys文件中
$ ssh-copy-id -i test.pub root@xx.xx.xx.xx # 执行此命令
# 以下为输出
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
The authenticity of host 'xx.xx.xx.xx (xx.xx.xx.xx)' can't be established.
ECDSA key fingerprint is SHA256:VZtcMgFfOx6M/5GAGlcCPm5fH6KmSL/pXoAv6ol4nzM.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@xx.xx.xx.xx's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@xx.xx.xx.xx'"
and check to make sure that only the key(s) you wanted were added.
3.测试免密登录
$ ssh root@xx.xx.xx.xx
Last login: Wed Apr 6 15:28:42 2022 from xx.xx.xx.xx
[root@hostname ~]$
4.继续添加第二个用户的免密
循环2,3步骤后发现无法实现免密登录,经查资料和实际验证,以下方法可解决问题。
[root@hostname ~]# vi /etc/ssh/sshd_config
#StrictModes yes
StrictModes no
[root@hostname ~]# systemctl restart sshd
结束语
- ssh免密是由客户端(远程发起方)生成密匙和公钥,并将公钥传至服务端(被远程方),一个主机免密登录多主机,只需将主机上的公钥导入到多个主机上即可。
- StrictModes参数默认是开启的,网上搜到相关的解释不是很清楚,这里就不贴出来了,因我这里是个人的开发机器,正式环境建议了解清楚参数相关作用和影响后再使用