ssh-key秘钥无密码登录和批量分发
A机器上生成ssh密钥对,实现能无密码连接登录到B机器和C机器
A机器:192.168.231.128 B机器:192.168.231.129 C机器:192.168.231.137
A机器上:192.168.231.128
[root@localhost ~]# ssh-keygen -t rsa #下面一路回车,不用输密码
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
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:
56:38:6b:e3:61:14:1f:d8:cb:4f:21:36:a1:a9:00:74 root@localhost.localdomain
The key's randomart image is:
+--[ RSA 2048]----+
| .o E .oo. |
| o .*=.. |
| . *oo+ . |
| . o +o . |
| . S o |
| = o . |
| . |
| |
| |
+-----------------+
[root@localhost ~]# ls /root/.ssh/
id_rsa id_rsa.pub
[root@localhost ~]# yum -y install openssh openssh-clients openssh-server #若没有ssh命令和ssh-copy-id等时候的安装
[root@localhost ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.231.129 #或仅IP
The authenticity of host '192.168.231.129 (192.168.231.129)' can't be established.
RSA key fingerprint is bf:2a:f6:bf:95:ac:c8:5c:c9:ae:e6:74:71:f4:ea:da.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.231.129' (RSA) to the list of known hosts.
root@192.168.231.129's password: #第一次需要输入对方用户密码:123456
Now try logging into the machine, with "ssh 'root@192.168.231.129'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
[root@localhost ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.231.137 #或仅IP
The authenticity of host '192.168.231.137 (192.168.231.137)' can't be established.
RSA key fingerprint is bf:2a:f6:bf:95:ac:c8:5c:c9:ae:e6:74:71:f4:ea:da.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.231.137' (RSA) to the list of known hosts.
root@192.168.231.137's password: #第一次需要输入对方用户密码:123456
Now try logging into the machine, with "ssh 'root@192.168.231.137'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
[root@localhost ~]# ssh root@192.168.231.129 'ifconfig |head -3'
eth0 Link encap:Ethernet HWaddr 00:0C:29:06:81:24
inet addr:192.168.231.129 Bcast:192.168.231.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe06:8124/64 Scope:Link
[root@localhost ~]# ssh root@192.168.231.137 'ifconfig |head -3'
eth1 Link encap:Ethernet HWaddr 00:0C:29:58:BE:E5
inet addr:192.168.231.137 Bcast:192.168.231.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe58:bee5/64 Scope:Link
#vim fenfa.sh #批量分发,根据情况使用for循环即可
#!/bin/bash
scp /tmp/a.txt root@192.168.231.129 端口号改变时,需要加参数: -P 端口号
scp /tmp/a.txt root@192.168.231.137
注意:ssh-copy命令格式有两种:1)ssh-copy-id 远端用户@远端IP #或仅IP
2)ssh-copy-id -i /root/.ssh/id_rsa.pub 远端用户@远端IP #或仅IP
如果对运维课程感兴趣,可以在b站上搜索我的账号: 运维实战课程,可以关注我,学习更多免费的运维实战技术视频