如上,A机器经常需远程操作B机器,传输文件到B机器,每次输入帐号密码过于繁琐,下文通过ssh公钥能解免密码操作问题。
二、解决
1.方案
SSH认证采用公钥与私钥认证方式。
2.步骤
1) A机器生成公钥/私钥对
[root@host-08 ~]# ssh-keygen -t rsa -P ''
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
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:
a7:e3:23:45:e4:a2:22:d0:8d:21:f8:fb:9a:18:b7:f2 root@host-08
The key's randomart p_w_picpath is:
+--[ RSA 2048]----+
|. |
|o . . |
| + + o |
|. + . . o |
|. . . oS . |
|. o . .o |
|...o .o |
|.+ o. .... |
|.oE. ... |
+-----------------+
说明
1. -P表示密码,-P '' 就表示空密码,也可以不用-P参数,这样就要三次回车,用-P就一次回车。
该命令将在/root/.ssh目录下面产生一对密钥id_rsa和id_rsa.pub。2. 一般采用的ssh的rsa密钥:
id_rsa 私钥
id_rsa.pub 公钥
下述命令产生不同类型的密钥
ssh-keygen -t dsa
ssh-keygen -t rsa
ssh-keygen -t rsa1
2) B机器建.ssh目录
[root@host-100 ~]# mkdir .ssh
说明
已有.ssh目录则不需要建立,没有则建.ssh目录
3) 将A机器生成的公钥拷贝到B机器
[root@host-08 ~]# scp -P 28888 ~/.ssh/id_rsa.pub root@192.168.1.100:/root/.ssh/authorized_keys
The authenticity of host '[192.168.1.100]:28888 ([192.168.1.100]:28888)' can't be established.
RSA key fingerprint is d4:a5:96:40:80:cb:c6:b9:7d:28:46:43:0c:95:49:84.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[192.168.1.100]:28888' (RSA) to the list of known hosts.
root@192.168.1.100's password:
id_rsa.pub 100% 396 0.4KB/s 00:00
[root@host-08 ~]#
说明
1.B机器ssh端口不是默认端口所以需要加参数 "-P 实际端口 "
2.B机器保存A机器公钥目录为$HOME/.ssh,公钥scp拷贝时重命名为 authorized_keys
4) B机器更改authorized_keys(A机器公钥)文件权限
[root@host-100 ~]# chmod 600 /root/.ssh/authorized_keys
----------------------------
至此,免密码配置已完毕。如想要B机器也免密码登录A机器,如上步骤目标机器调换一下即可。
5) 测试
SSH免密码登录
[root@host-08 ~]# ssh -p28888 -l root 192.168.1.100
Last login: Tue Jun 14 15:02:37 2016 from 192.168.1.8
[root@host-203 ~]$
SCP免密码传输文件
[root@host-08 ~]# scp -P 28888 -r /root/findyou.war root@192.168.1.100:/root/
findyou.war 100% 8005KB 7.8MB/s 00:01
[root@host-08 ~]#