Linux免密登录
一、生成免密登录公钥
ssh-keygen -t rsa
如下:
[root@VM-0-9-centos /]# ssh-keygen -t rsa 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: SHA256:ZyZSw/Ciok0MqO1My3qgo9K9ONQBxkEkz8tymflz82Q root@VM-0-9-centos The key's randomart image is: +---[RSA 2048]----+ |.++. . | |.++ + | |o.o. . = | |.= =.. o . | |o &.... S + | |.@.+. . = | |o+*.o o E | |+.+..o = | |=o.... . | +----[SHA256]-----+
注意:如果每生成过此公钥,只需一路回车即可。
二、查看公钥
公钥的路径:
Enter file in which to save the key (/root/.ssh/id_rsa):
即:/root/.ssh
[root@VM-0-9-centos /]# cd /root/.ssh/ [root@VM-0-9-centos .ssh]# ls authorized_keys id_rsa id_rsa.pub [root@VM-0-9-centos .ssh]#
authorized_keys:存放远程免密登录的公钥,主要通过这个文件记录多台机器的公钥 id_rsa: 生成的私钥文件 id_rsa.pub: 生成的公钥文件 know_hosts: 已知的主机公钥清单 如果希望ssh公钥生效需满足至少下面两个条件: 1) .ssh目录的权限必须是700 2) .ssh/authorized_keys文件权限必须是600
三、实现远程免密登录
在本地(或服务器A)上实现免密登录服务器B,需要将本地(或服务器A)的公钥(/root/.ssh/id_rsa.pub文件内容)配置到服务器B的/root/.ssh/authorized_keys里即可,多个公钥注意换行。
四、配置方式
4.1 通过ssh-copy-id的方式
ssh-copy-id -i ~/.ssh/id_rsa.pub <username@romte_ip>
如下:
liumeng@liumengdeMacBook-Pro .ssh % ssh-copy-id -i ~/.ssh/id_rsa.pub root@106.53.***.*** /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/liumeng/.ssh/id_rsa.pub" /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@106.53.***.***'s password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'root@106.53.***.***'" and check to make sure that only the key(s) you wanted were added.
4.2 SCP方式
scp -p ~/.ssh/id_rsa.pub root@<remote_ip>:/root/.ssh/authorized_keys
如下:
liumeng@liumengdeMacBook-Pro .ssh % scp -P 22 ~/.ssh/id_rsa.pub root@106.53.***.***:/root/.ssh/authorized_keys root@106.53.***.***'s password: id_rsa.pub 100% 588 7.8KB/s 00:00 liumeng@liumengdeMacBook-Pro .ssh %
4.3 通过Ansible实现批量免密
将需要做免密操作的机器hosts添加到/etc/ansible/hosts下
4.4 手动复制粘贴
将本地id_rsa.pub文件的内容拷贝至远程服务器的~/.ssh/authorized_keys文件中。
结束!