说明
jenkins构建时需要连接远程服务器并且执行脚本,这时就需要配置ssh免密钥登录。jenkins构建时都是以jenkins用户进行操作,所以要以jeknins用户来配置免密钥登录。本教程以用户名qiaofeng为例说明。 A:192.168.10.78, B:192.168.10.76,需求:A登录B时免密钥。
命令
ssh-keygen -t rsa 产生公钥与私钥对
ssh-copy-id 将本机的公钥复制到远程机器的authorized_keys文件中
步骤
1. 切换到qiaofeng用户
su - qiaofeng
2. 用ssh-keygen -t rsa产生密钥对
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
[qiaofeng@jenkins ~]$ ssh
-
keygen
-
t rsa
Generating public
/
private rsa key pair.
Enter
file
in
which to save the key (
/
home
/
qiaofeng
/
.ssh
/
id_rsa):
Enter passphrase (empty
for
no passphrase):
Enter same passphrase again:
Your identification has been saved
in
/
home
/
qiaofeng
/
.ssh
/
id_rsa.
Your public key has been saved
in
/
home
/
qiaofeng
/
.ssh
/
id_rsa.pub.
The key fingerprint
is
:
56
:
3e
:
89
:fc:
6f
:
8c
:
4d
:
06
:ee:
5f
:b9:
6b
:a3:
6a
:d9:e2 qiaofeng@jenkins
The key's randomart image
is
:
+
-
-
[ RSA
2048
]
-
-
-
-
+
| |
| |
| . |
| .
+
.. |
| S.
+
. |
| . ...o . |
| ..O o |
|
*
.
=
.o. |
| oE
=
+
ooo |
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
|
3. 用ssh-copy-id将公钥从A复制到B
1
2
3
4
5
|
[qiaofeng@jenkins ~]$ ssh
-
copy
-
id
-
i ~
/
.ssh
/
id_rsa.pub
"-p 22223 root@192.168.10.76"
root@
192.168
.
10.76
's password:
Now
try
logging into the machine, with
"ssh '-p 22223 root@192.168.10.76'"
,
and
check
in
:
.ssh
/
authorized_keys
to make sure we haven
't added extra keys that you weren'
t expecting.
|
注意
ssh-copy-id 将key写到远程机器的 ~/ .ssh/authorized_key.文件中。
如果你远程服务器SSH端口没有修改过,可以不用加-p 22223,要特别注意双引号。
当然你复制文件到远程服务器也可以用SCP命令。
4. 验证登录
[qiaofeng@jenkins ~]$ ssh -p 22223 root@192.168.10.76
Last login: Mon Apr 17 15:10:04 2017 from 192.168.10.78
[root@hundsun ~]#
扩展
1. 现在实现了需求,如果你想B访问A时也免密钥,只要在B上按上面的步骤来。
2. 如果添加指纹的时候提示添加失败,是因为你以前添加过了这个ip的指纹。
解决办法:将.ssh目录的known_hosts文件删除掉。也可以打开这个文件把对应ip的那条记录删除。
3. 注意文件权限的问题
A
[qiaofeng@jenkins ~]$ ll .ssh/
-rw-------. 1 qiaofeng qiaofeng 1671 4月 19 05:10 id_rsa
-rw-r--r--. 1 qiaofeng qiaofeng 398 4月 19 05:10 id_rsa.pub
-rw-r--r--. 1 qiaofeng qiaofeng 417 4月 19 05:08 known_hosts
B
-rw------- 1 root root 1217 Apr 21 10:46 /root/.ssh/authorized_keys
本文转自pizibaidu 51CTO博客,原文链接:http://blog.51cto.com/pizibaidu/1918027,如需转载请自行联系原作者