简体   繁体   中英

SSH into a remote server in a Jenkins pipeline using withCredentials

I want to SSH into a server to perform some tasks in my Jenkins pipeline.

Here are the steps that I went through.

  1. In my remote server, I used ssh-keygen to create id_rsa and id_rsa.pub
  2. I copied the string in the id_rsa and pasted to the Private Key field in the Global Credentials menu in my Jenkins server.

在此处输入图片说明

  1. In my Jenkinsfile, I do

    stage('SSH into the server') { steps { withCredentials([sshUserPrivateKey( credentialsId: '<ID>', keyFileVariable: 'KEY_FILE')]) { sh ''' more ${KEY_FILE} cat ${KEY_FILE} > ./key_key.key eval $(ssh-agent -s) chmod 600 ./key_key.key ssh-add ./key_key.key cd ~/.ssh echo "ssh-rsa ... (the string from the server's id_rsa.pub)" >> authorized_keys ssh root@<server_name> docker ps ''' } } }

It pretty much creates an ssg-agent using the private key of the remote server and adds a public key to the authorized key.

This as a result gives me, Host key verification failed

I just simply wanted to ssh into the remote server, but I keep facing this issue. Any help?

LOG

++ ssh-agent -s
+ eval 'SSH_AUTH_SOCK=/tmp/ssh-xfcQYEfiyfRs/agent.26353;' export 'SSH_AUTH_SOCK;' 'SSH_AGENT_PID=26354;' export 'SSH_AGENT_PID;' echo Agent pid '26354;'
++ SSH_AUTH_SOCK=/tmp/ssh-xfcQYEfiyfRs/agent.26353
++ export SSH_AUTH_SOCK
++ SSH_AGENT_PID=26354
++ export SSH_AGENT_PID
++ echo Agent pid 26354
Agent pid 26354
+ chmod 600 ./key_key.key
+ ssh-add ./key_key.key
Identity added: ./key_key.key (./key_key.key)
+ ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i ./key_key.key root@<server> docker ps
Warning: Permanently added '<server>, <IP>' (ECDSA) to the list of known hosts.

                                 WARNING!!!
                    READ THIS BEFORE ATTEMPTING TO LOGON

      This System is for the use of authorized users only.  ....



Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

It is failing because of StrictHostKeyChecking enabled. Change your ssh command as below and it should work fine.

ssh -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking=no" root@<server_name> docker ps

StrictHostKeyChecking=no will disable the prompt for host key verification.

UserKnownHostsFile=/dev/null will skip the host key checking by sending the key to /dev/null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM