Linux-设置免密登陆

生成密钥

1
$ ssh-keygen -t rsa -P ''

会生成如下:
~/.ssh/
~/.ssh/authorized_keys # 存放远程免密登录的公钥,主要通过这个文件记录多台机器的公钥
~/.ssh/id_rsa # 生成的私钥文件
~/.ssh/id_rsa.pub # 生成的公钥文件
~/.ssh/know_hosts # 已知的主机公钥清单

设置本机免密登陆

1
$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

设置远程免密登陆

通过ssh-copy-id的方式

语法

1
$ ssh-copy-id -i ~/.ssh/id_rsa.pub user@<romte_ip>

示例

1
$ ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.100.10

提示

如果未安装openssh-clients,会提示:

1
-bash: ssh-copy-id: command not found

解决办法:

1
$ yum install openssh-clients

通过scp将内容写到对方的文件中

语法

1
scp -p ~/.ssh/id_rsa.pub root@<remote_ip>:/root/.ssh/authorized_keys

示例

1
$ scp -p ~/.ssh/id_rsa.pub root@192.168.100.10:/root/.ssh/authorized_keys

通过Ansible实现批量免密

语法

1
$ ansible <groupname> -m authorized_key -a "user=root key='{{ lookup('file','/root/.ssh/id_rsa.pub') }}'" -k

示例

1
$ ansible node1 -m authorized_key -a "user=root key='{{ lookup('file','~/.ssh/id_rsa.pub') }}'" -k
坚持原创技术分享,您的支持将鼓励我继续创作!