ssh免密登录
版权说明:本文系博主通过各种渠道学习整理发表或者全文转载自其他平台,作为学习笔记,不能保证所有知识点是完全正确以及表达无误,用于生产环境配置时请斟酌。如有错误或建议请联系。转载请注明出处,侵删联系:linuxops@foxmail.com。感谢各位!
有时候在服务器之间复制文件或者一些自动化的操作时候需要用到免密登录。具体操作如下:
使用到的命令有:
sh-keygen 产生公钥与私钥对.
ssh-copy-id 将本机的公钥复制到远程机器的authorized_keys文件中
假如有两台服务器:
A:1.2.3.4
B:5.6.7.8
效果:在B服务器上免密登录A服务器
操作步骤:
一、现在B上使用ssh-keygen产生密钥对
[root@HYZ ~]# ssh-keygen -t rsa #等同于ssh-keygen 不加任何参数输入也可以
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
2d:af:68:ce:60:01:fe:f1:93:75:17:93:a6:c0:a8:4c root@HYZ
The key's randomart image is:
+--[ RSA 2048]----+
| |
| o . |
| . E . o = |
| . + . o o o |
| . = S + . |
| . + o + . |
| + + . |
| . o.o . |
| o+ . |
+-----------------+
[root@HYZ ~]# #一路回车,不要填写密码
二、使用ssh-copy-id命令将公钥发送给被登陆服务器的~/.ssh/authorized_keys
文件
[root@HYZ ~]# ssh-copy-id -p 2200 -i ~/.ssh/id_rsa.pub root@1.2.3.4 #-p指定端口
The authenticity of host '[ 1.2.3.4]:2200 ([ 1.2.3.4]:3137)' can't be established.
ECDSA key fingerprint is bd:26:09:72:62:bc:e3:56:fa:73:e4:2e:81:52:2d:4d.
Are you sure you want to continue connecting (yes/no)? 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@ 1.2.3.4's password: #输入1.2.3.4服务器密码
Number of key(s) added: 1
Now try logging into the machine, with: "ssh -p '2200' ' 1.2.3.4'"
and check to make sure that only the key(s) you wanted were added.
[root@HYZ ~]#
以上两步操作完成 B服务器就可以免密登录A服务器了。
说明:1、公钥存储在被登陆服务器的~/.ssh/authorized_keys文件中,删除相应的公钥就可取消免密登录。2、手动将公钥添加到被登陆服务器的~/.ssh/authorized_keys文件也可以生效。