如何通过执行 shell 命令在 Jenkins 作业中使用 ssh 凭据

问题描述 投票:0回答:2

我一直在尝试允许 Jenkins 从执行 shell 命令中连接到 SSH 服务器,但没有成功。

我已经安装了 SSH 凭据插件,并添加了 SSH 站点的凭据 - 包括密钥。我已经为凭证提供了 my-server-ssh 的 ID - 认为这就是我可以从执行 shell 命令引用它的方式 - 但我认为这可能是我错的地方。

通过执行 shell 命令,我正在这样做:

ssh my-server-ssh ls

但这会产生此错误: ssh:无法解析主机名 my-server-ssh:名称或服务未知

所以看来指定ID是行不通的。有人成功做过类似的事情吗?

jenkins ssh jenkins-plugins
2个回答

0
投票
我想出了如何做到这一点(至少在当前版本的詹金斯上)。

Manage Jenkins | Credentials | System | Global Credentials +Add Credential Kind: Ssh with key Id: my-server-ssh Username: [required username] Private Key Enter Directly: Copy/paste the private key generated from ssh-keygen or the like Within Freestyle job | Configure | Build Environment | Use Secret Text or File Key File Variable: SshCredentialKeyFile Passphrase Variable: SshCredentialPassphrase Username Variable: SshCredentialKeyUsername Select my-server-ssh in the Credentials drop down Within Freestyle job | Configure | Execute Shell: ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i $SshCredentialKeyFile -l $SshCredentialUsername [ip_address] [commmand]
注意,我必须使用 StrictHostKey/UserKnownHosts 选项,否则第一次运行时会提示输入“接受”密钥,并且无密码登录失败,并显示错误“主机密钥验证失败”。仅禁用此选项并不是一种好的安全实践,人们可以在 jenkins 代理上手动一次性创建一个有效的known_hosts 文件。

注意,也可以在 ssh 密钥上启用密码,但我不需要这样做。

© www.soinside.com 2019 - 2024. All rights reserved.