环境2台linux服务器:node1 192.168.X.234
node2 192.168.X.242
演示用node1无密码登陆node2,秘钥登陆是单向的,如果要双向登陆再反过来配置一下就可以
在node1上面创建密钥对
#在/root/.ssh/目录下执行ssh-keygen 一直回车就行,如果有需要也可以给密码设置密码
[root@--X- .ssh]# 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:
ec::8d:a2:2e:a4::f2:b4::4c::::: root@---.baicheng.com
The key's randomart image is:
+--[ RSA ]----+
| +.. |
| o E |
| = |
| . o + . |
| + o o S |
| = = o |
|= B + . |
|+ * |
|.. |
+-----------------+
ls查看 目录下面多了2个文件就是 公钥和私钥,公钥内容需要添加到给你想登陆的那台机器的任何用户下的.ssh/authorized_keys,添加到哪个用户下面就用那个用户登陆就可以,这里我们添加到node2
[root@--X- .ssh]# ls
id_rsa id_rsa.pub
用ssh-copy-id 可以直接把id_rsa.pub里面的内容追加到对方的.ssh/authorized_keys里面
[root@--X- .ssh]# ssh-copy-id "-p62387 xiewenming@192.168.X.242"
Address 192.168.X.242 maps to localhost, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!
Now try logging into the machine, with "ssh '-p62387 xiewenming@192.168.X.242'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting. [root@--- .ssh]#
注意:如果默认端口不是22,那么ssh-copy-id "-p62387 xiewenming@192.168.X.242" 这里需要加引号,否则会报下面的错误
[root@--X- .ssh]# ssh-copy-id -p62387 xiewenming@192.168.X.242
Pseudo-terminal will not be allocated because stdin is not a terminal.
ssh: Could not resolve hostname umask ; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys; test -x /sbin/restorecon && /sb: Name or service not known
在node2的节点上查看,authorized_keys权限是600,如果是自己创建的文件得注意这个权限问题,.ssh目录文件夹权限为700
[root@--X- .ssh]# pwd
/home/xiewenming/.ssh
[root@--X- .ssh]# cat authorized_keys
AAAAB3NzaC1yc2EAAAABIwAAAQEA15QNqu6N0kkNv+e4qXD+Gz8TqWo7LJKeumuFAMD2ZDH0/MfKPKCfxOGv8k/cMB1XRKYFTuxR/ZW7HqmNK1wpppCqccxjKj/vOeWjuk16x2rMqqjkWBIedw7a/fGP87GC0DmOAe3bzWbqDY0rGA5jWR+YBItGES2GmW3889jJRhgcmQO2qsCnxfQ8g1D6XfpKSXCe7qvYtsqRn7Jcw35I39vx6kxpxgjtNobEo2Xw7tfx9n64poNzi72e/UF7mZSB5EZgKLM8uxw4wgBljB2yX9Cnsc5y4Qs+VzUaI7TyzR4RFTWiukOKCPEjxJPJ71E9/HL44Qi8LOTTBp/20T7JLw== root@---.xxx.com
到这里就已经配置完成可以在node1上面不用密码登陆到node2上面
[root@--X- .ssh]# ssh xiewenming@192.168.X.242
Address 192.168.X.242 maps to localhost, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!
Last login: Tue Aug :: from 192.168.X.234
[xiewenming@--- ~]$ ifconfig |grep 192.168
inet addr:192.168.3.242 Bcast:192.168.X.255 Mask:255.255.255.0
ps:ssh-copy-id 是一个很好用的命令,如果没有这个命令有的运维人员经常拷贝公钥内容放到authorized_keys,那么拷贝经常出现的问题是原来公钥内容是一行,拷贝就会成了多行,需要手动调格式,降低了工作效率,有了上面的ssh-copy-id 基础完全可以写脚本批量完成对其它服务器的操作