SCP didn't work in Jenkins - jenkins

When I use the following codes in terminal, it works well.
#!/usr/bin/expect -f
spawn scp /Users/Shared/Jenkins/workspace/testslave/XXXXXX aaa#10.XXX.XXX.XX:/tmp/XXXX
expect "*assword:"
send "password\r"
interact
but when I copy the content to the Jenkins,the Jenkins didn't copy the file to the destination,and with no error.

A cleaner approach is to generate a public/private key with no pass-phrase and to use it as an authentication method.
The steps are:
Generate the key by executing ssh-keygen
Copy the public key (usually id_rsa.pub) to the .ssh folder of the user in the destination host. In your case it seems to be /Users/Shared/Jenkins/.ssh
Execute: scp -i id_rsa /Users/Shared/Jenkins/workspace/testslave/XXXXXX aaa#10.XXX.XXX.XX:/tmp/XXXX

Related

not able to pip install from private repo in docker [duplicate]

I'm on Mac Snow Leopard and I just installed git.
I just tried
git clone git#thechaw.com:cakebook.git
but that gives me this error:
Initialized empty Git repository in `/Users/username/Documents/cakebook/.git/`
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
What am I missing?
I've also tried doing ssh-keygen with no passphase but still same error.
If the user has not generated a ssh public/private key pair set before
This info is working on theChaw but can be applied to all other git repositories which support SSH pubkey authentications. (See [gitolite][1], gitlab or github for example.)
First start by setting up your own public/private key pair set. This
can use either DSA or RSA, so basically any key you setup will work.
On most systems you can use ssh-keygen.
First you'll want to cd into your .ssh directory. Open up the terminal and run:
cd ~/.ssh && ssh-keygen
Next you need to copy this to your clipboard.
On OS X run: cat id_rsa.pub | pbcopy
On Linux run: cat id_rsa.pub | xclip
On Windows (via Cygwin/Git Bash) run: cat id_rsa.pub | clip
On Windows (Powershell) run: Get-Content id_rsa.pub | Set-Clipboard (Thx to #orion elenzil)
Add your key to your account via the website.
Finally setup your .gitconfig.
git config --global user.name "bob"
git config --global user.email bob#...
(don't forget to restart your command line to make sure the config is reloaded)
That's it you should be good to clone and checkout.
Further information can be found at https://help.github.com/articles/generating-ssh-keys (thanks to #Lee Whitney)
[1]: https://github.com/sitaramc/gitolite
-
If the user has generated a ssh public/private key pair set before
check which key have been authorized on your github or gitlab account settings
determine which corresponding private key must be associated from your local computer
eval $(ssh-agent -s)
define where the keys are located
ssh-add ~/.ssh/id_rsa
More extensive troubleshooting and even automated fixing can be done with:
ssh -vT git#github.com
Alternatively, according to below comments, we could issue:
ssh -vT git#gitlab.com
or substitute gitlab/github with whatever Git Instance your organisation is running.
Source: https://help.github.com/articles/error-permission-denied-publickey/
This error can happen when you are accessing the SSH URL (Read/Write) instead of Git Read-Only URL but you have no write access to that repo.
Sometimes you just want to clone your own repo, e.g. deploy to a server. In this case you actually only need READ-ONLY access. But since that's your own repo, GitHub may display SSH URL if that's your preference. In this situation, if your remote host's public key is not in your GitHub SSH Keys, your access will be denied, which is expected to happen.
An equivalent case is when you try cloning someone else's repo to which you have no write access with SSH URL.
In a word, if your intent is to clone-only a repo, use HTTPS URL (https://github.com/{user_name}/{project_name}.git) instead of SSH URL (git#github.com:{user_name}/{project_name}.git), which avoids (unnecessary) public key validation.
Update: GitHub is displaying HTTPS as the default protocol now and this move can probably reduce possible misuse of SSH URLs.
The github help link helped me sort out this problem. Looks like the ssh key was not added to the ssh-agent. This is what I ended up doing.
Command 1:
Ensure ssh-agent is enabled. The command starts the ssh-agent in the background:
eval "$(ssh-agent -s)"
Command 2:
Add your SSH key to the ssh-agent:
ssh-add ~/.ssh/id_rsa
Got the same error report.
Fixed with using the HTTPS instead of the SSH protocol. Since I don't want to set "SSH keys" for a test PC.
Change URL to HTTPS when clone:
git clone https://github.com/USERNAME/REPOSITORY.git
My problem is a little bit different: I have the URL set to SSH when adding an existing local repo to remote, by using:
git remote add origin ssh://github.com/USERNAME/REPOSITORY.git
To fix it, reset the URL to HTTPS:
git remote set-url origin https://github.com/USERNAME/REPOSITORY.git
BTW, you may check your URL using the command:
git remote -v
origin https://github.com/USERNAME/REPOSITORY.git (fetch)
origin https://github.com/USERNAME/REPOSITORY.git (push)
Hope this will help some one like me. :D
Another possibility on Windows, which is not covered in any of these answers, and is not covered in the git or github docs on troubleshooting:
git may be using a different openssh executable than you think it is.
I was receiving the Permission denied (public key) error when trying to clone or pull from github and ssh.dev.azure.com, and I'd followed all the instructions and verified that my SSH keys were setup correctly (from SSH's standpoint) using ssh -vT git#github.com and ssh -vT git#ssh.dev.azure.com. And was still getting these errors:
git#github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
I eventually figured out that the problem is that Git for Windows, and Windows, both have their own versions of openssh. This is documented here: https://github.com/desktop/desktop/issues/5641
I was relying on the Windows ssh-agent service to store my ssh key passphrases, so git (with it's separate version of openssh) couldn't read my private keys. I consider it a bug that this error message is used - it's misleading.
The fix was:
git config --global core.sshCommand "'C:\Windows\System32\OpenSSH\ssh.exe'"
Or in your ~/.gitconfig:
[core]
sshCommand = 'C:\\Windows\\System32\\OpenSSH\\ssh.exe'
Perhaps this will be fixed in git for Windows soon, but this is the 2nd time I've wasted time on this issue.
I was struggling with the same problem that's what I did and I was able to clone the repo. I followed this procedure for Mac.
First Step: Checking if we already have the public SSH key.
Open Terminal.
Enter ls -al ~/.ssh to see if existing SSH keys are present:
Check the directory list to see if you already have a public SSH key. Default public is one of the following d_dsa.pub, id_ecdsa.pub, id_ed25519.pub, id_rsa.pub.
If you don't find then go to step 2 otherwise follow step 3
Step 2: Generating public SSH key
Open Terminal.
Enter the following command with a valid email address that you use for github ssh-keygen -t rsa -b 4096 -C "your_email#example.com"
You will see the following in your terminal Generating public/private rsa key pair. When it prompts to"Enter a file in which to save the key," press Enter. This accepts the default file location. When it prompts to Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter] Just press enter again.
At the prompt, "Type a secure passphrase. Enter passphrase (empty for no passphrase): [Type a passphrase]" press enter if you don't want to Enter same passphrase again: [Type passphrase again] press enter again
This will generate id_rsa.pub
Step 3: Adding your SSH key to the ssh-agent
Interminal type eval "$(ssh-agent -s)"
Add your SSH key to the ssh-agent. If you are using an existing SSH key rather than generating a new SSH key, you'll need to replace id_rsa in the command with the name of your existing private key file. Enter this command $ ssh-add -K ~/.ssh/id_rsa
Now copy the SSH key and also add it to you github account
In terminal enter this command with your ssh file name pbcopy < ~/.ssh/id_rsa.pub This will copy the file to your clipboard
Now open you github account Go to Settings > SSH and GPG keys > New SSH key Enter title and paste the key from clipboard and save it. Voila you're done.
This works for me:
ssh-add ~/.ssh/id_rsa
Visual guide (Windows)
1 of 2. Git batch side
1.1. Open git batch (Download her)
1.2. Paste the text below (Change to your GitHub account email)
$ ssh-keygen -t rsa -b 4096 -C "your_email#example.com"
1.3. Press Enter (Accepts the default file location)
1.4. Click Enter Twice (Or set SSH key passphrases - Gitbub passphrases docs)
> Enter passphrase (empty for no passphrase): [Type a passphrase]
> Enter same passphrase again: [Type passphrase again]
1.5. The key generate:
Your identification has been saved in /c/Users/user/.ssh/id_rsa...
1.6. Copy the SSH key to your clipboard.
$ clip < ~/.ssh/id_rsa.pub
2 of 2. Github website user side
Under user setting
SSH and GPG keys => New SSH key:
Paste the code from step 1.6
Done :)
If someone doesn't want to use SSH use HTTPS :
Github docs: https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh
If your problem appears out of the blue recently (the latter half of 2021), it may have been caused by incompatible hash algorithms.
As of this post (Oct 2021), the latest version of Git for windows is 2.33.1 (release note), who has embraced the latest OpenSSH 8.8p1 (release note), who in turn has deprecated SHA-1. Meanwhile, if your remote Git repository still sticks to SHA-1, you'll fail the authentication.
To see whether you could have fallen into this case, check the version of your software by:
ssh -V
git --version
Then you should check the "Potentially-incompatible changes" section of OpenSSH 8.8/8.8p release note.
TL;DR
Solution 1: Enable SHA-1 again by adding this to your ~/.ssh/config file:
Host <remote>
HostkeyAlgorithms +ssh-rsa
PubkeyAcceptedAlgorithms +ssh-rsa
Remember to replace <remote> with the hostname of your remote repository.
Solution 2: Regenerate your key pair using ECDSA or Ed25519, instead of RSA. For example:
ssh-keygen -t ecdsa -C <comment>
Remember to replace <comment> with your own mnemonic phrase. Then, upload the generated public key to your remote repository.
FYI, I encountered this prompt message when accessing Gitee.com, who uses golang.org/x/crypto/ssh on their server and has posted a page on this issue here (in Mandarin).
git#gitee.com: Permission denied (publickey).
Note that (at least for some projects) you must have a github account with an ssh key.
Look at the keys listed in your authentication agent (ssh-add -l)
(if you don't see any, add one of your existing keys with ssh-add /path/to/your/key (eg: ssh-add ~/.ssh/id_rsa))
(if you don't have any keys, first create one. See: http://rcsg-gsir.imsb-dsgi.nrc-cnrc.gc.ca/documents/internet/node31.html or just google ssh-keygen)
To verify that you have a key associated with your github account:
Go to: https://github.com/settings/ssh
You should see at least one key with a hash key matching one of the hashes you saw when you typed ssh-add -l just a minute ago.
If you don't, add one, then try again.
I met the same issue because of I was thought the difference between SSH and HTTPS is
https://github.com/USERNAME/REPOSITORY.git
ssh://github.com/USERNAME/REPOSITORY.git
So I changed from HTTPS to SSH just by changing https:// to ssh:// nothing on the end of the url was changed.
But the truth is:
https://github.com/USERNAME/REPOSITORY.git
git#github.com:USERNAME/REPOSITORY.git
Which means I changed ssh://github.com/USERNAME/REPOSITORY.git to git#github.com:USERNAME/REPOSITORY.git it works.
Stupid error but hope helps someone!
These are the steps I followed in windows 10
Open Git Bash.
Generate Public Key:
ssh-keygen -t rsa -b 4096 -C "youremailaddress#xyz.com"
Copy generated key to the clipboard (works like CTRL+C)
clip < ~/.ssh/id_rsa.pub
Browser, go to Github => Profile=> Settings => SSH and GPG keys => Add Key
Provide the key name and paste clipboard (CTRL+V).
Finally, test your connection (Git bash)
ssh -T git#github.com
Thanks!
Please try this if nothing is worked out
Generate personal Access token (Setting -> Developer settings -> Personal access tokens -> Generate new token)
git remote set-url origin https://<TOEKN>#github.com/USERNAME/REPOSITORY.git
Note: If a password popup comes, try to enter the token only (try twice)
I had a slight different situation, I was logged on to a remote server and was using git on the server, when I ran any git command I got the same message
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
The way I fixed it was by changing the file /etc/ssh_config on my Mac.
from
ForwardAgent no
to
ForwardAgent yes
I had to copy my ssh keys to the root folder.
Google Cloud Compute Engine running Ubuntu 18.04
sudo cp ~/.ssh/* /root/.ssh/
Solution using gh i.e. Github's official CLI
gh installation
brew install gh
gh login or authentication via cli
gh auth login
repo clone
gh repo clone <username or orgname>/<repo-name>
Example: gh repo clone keshavdulal/sample-repo
Rant: I too was bashing my head when git clone suddenly decided not to work anymore and I don't have the patience or brainpower to relearn ssh/public keys/cryptography from scratch just to clone a freaking repo I already have access to. Also surprised no one mentioned gh in the answers yet
Guys this is how it worked for me:
Open terminal and go to user [See attached image]
Open .ssh folder and make sure it doesn't have any file like id_rsa or id_rsa.pub otherwise sometimes it wont properly rewrite files
git --version [Check for git installation and version]
git config --global user.email "your email id"
git config --global user.name "your name"
git config --list [make sure you have set your name & email]
cd ~/.ssh
ssh-keygen, it prompts for saving file, allow it
cat ~/.ssh/id_rsa.pub [Access your public key & copy the key to gerrit settings]
Note: You should not be using the sudo command with Git. If you have a very good reason you must use sudo, then ensure you are using it with every command (it's probably just better to use su to get a shell as root at that point). If you generate SSH keys without sudo and then try to use a command like sudo git push, you won't be using the same keys that you generated
ALWAYS CHECK GITHUB FOR SSH-KEYS GENERATION PROCEDUR, NOT SOME OUTDATED BLOG
https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
There you can see that keys are generated with:
ssh-keygen -t ed25519 -C "your_email#example.com"
So algorithm is ed25519 not rsa or anything else.
Are you in a corporate environment? Is it possible that your system variables have recently changed? Per this SO answer, ssh keys live at %HOMEDRIVE%%HOMEPATH%\.ssh\id_rsa.pub. So if %HOMEDRIVE% recently changed, git doesn't know where to look for your key, and thus all of the authentication stuff.
Try running ssh -vT git#github.com. Take note of where the identity file is located. For me, that was pointing not to my normal \Users\MyLogin but rather to a network drive, because of a change to environment variables pushed at the network level.
The solution? Since my new %HOMEDRIVE% has the same permissions as my local files, I just moved my .ssh folder there, and called it a day.
I hit this error because I needed to give my present working directory permissions 700:
chmod -R 700 /home/ec2-user/
On Windows, make sure all your apps agree on HOME. Msys will surprisingly NOT do it for you. I had to set an environment variable because ssh and git couldn't seem to agree on where my .ssh directory was.
One of the easiest way
go to terminal-
git push <Git Remote path> --all
The basic GIT instructions did not make a reference to the SSH key stuff. Following some of the links above, I found a git help page that explains, step-by-step, exactly how to do this for various operating systems (the link will detect your OS and redirect, accordingly):
http://help.github.com/set-up-git-redirect/
It walks through everything needed for GITHub and also gives detailed explanations such as "why add a passphrase when creating an RSA key." I figured I'd post it, in case it helps someone else...
The easiest solution to this, when you are trying to push to a repository with a different username is:
git remote set-url origin https://USERNAME#github.com/USERNAME/PROJECTNAME.git
I helped the following:
Open Terminal (Git Bash)
Remove all files in directory .ssh or rename and create new .ssh folder.
To follow in the steps of the instructions:
Generating a new SSH key
Adding your SSH key to the ssh-agent
System: Windows 10.
In addition to Rufinus' reply, the shortcut to copy your ssh key to the clipboard in Windows is:
type id_rsa.pub | clip
Refs:
Print to standard output
Copy command line output to clipboard
If you have more than one key you may need to do
ssh-add private-keyfile
Its pretty straight forward. Type the below command
ssh-keygen -t rsa -b 4096 -C "youremailid#yourdomain.com"
Generate the SSH key. Open the file and copy the contents. Go to GitHub setting page , and click on SSH key . Click on Add new SSH key, and paste the contents here. That's it :) You shouldn't see the issue again.
I deleted node_modules/ package-lock.json and yarn.lock files. Ran npm i again. This resolved the issue for me.

remote github access is denied even though the public key is created and saved in my github profile

I have asked the same question on github but no response. So, I think here may be a better place to ask this kind of coding questions because this is the problem when I tried to do some coding work.
I would like to set up airflow with docker on MacBook Pro with macOS 10.14.x.
I have got zpencerq/docker-airflow:1.10.2 and followed the instructions at https://docs.docker.com/compose/install/#install-compose
Also, I have set up the ssh agent forward with the instructions at https://github.com/uber-common/docker-ssh-agent-forward
When I run:
docker-compose up -d
I got:
Collecting my-data-store from git+ssh://git#github.com/my-data-store.git#v.xx.xx.x#egg=my-data-store
Cloning ssh://git#github.com/my-data-store.git to /my/local/path
Permission denied (publickey).
fatal: Could not read from remote repository.
I have created ssh public key and added the ssh public key in my git profile. I have also added my private key.
I have tried some answers for this kind of question, but none of them work.
If I run the following command in Mac terminal, it works well.
git clone -q ssh://git#github.com/my_path/my-data-store.git /tmp/my_folder
Why docker-compose cannot do the same thing to access github ?
Do I miss something ?
Sounds like you haven't added your keys. Try this from inside your OSX terminal...
ssh-add
Then try again.
Why docker-compose cannot do the same thing to access github ?
Because it (docker) will look for your keys in $HOME/.ssh/id_rsa(.pub).
When you execute git clone -q ssh://git#github.com/... from your Mac, $HOME is your regular home directory.
But from a container, it is /root by default, or the one of the user.
You should mount those keys in your docker-compose.yml (or use secrets).
You can add to a container environment
-e GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=no -o User=<github user> -i <private key>"
When is full key text making by ssh-keygen

Deploying from Jenkins server to another server: Host key verification failed

I am trying to deploy to another server from Jenkins server, and I can't do it using Jenkins Build script.
When I am on the Jenkins server, I can deploy. For example:
:/var/lib/jenkins/workspace/MyProject$ scp my_file ubuntu#my_address:~/MyProject
Runs perfectly fine; however,
When I specify:
scp my_file ubuntu#my_address:~/MyProject
In "Execute Shell" under build in Jenkins window. I get the following error:
Host key verification failed.
I know that the first time I ran the above command directly on Jenkins server, I was prompted:
The authenticity of host 'my_address (my_address)' can't be established.
ECDSA key fingerprint is cf:4b:58:66:d6:d6:87:35:76:1c:aa:cf:9a:7c:78:cc.
Are you sure you want to continue connecting (yes/no)?
So I had to hit "yes" in order to continue. But since I already directly in the terminal, I don't have to do anything extra.
Second answer to this question: Jenkins Host key verification failed
indicates that, if I understand it correctly.
What am I missing? What can I do to fix my problem?
I got it working, I needed to do two things:
1) I had to use -o StrictHostKeyChecking=no:
scp -v -o StrictHostKeyChecking=no my_file ubuntu#my_address:~/MyProject
instead of:
scp my_file ubuntu#my_address:~/MyProject
2) I needed to copy my id_rsa to /var/lib/jenkins/.ssh
The /var/lib/jenkins/.ssh folder and files inside of it need to be owned by jenkins.
Old question but may be someone would find this useful:
ssh root#jenkinsMaster 'echo "$(ssh-keyscan -t rsa,dsa jenkinsSlave)" >> /root/.ssh/known_hosts'
Make sure that you're first settingup ssh connection to remote host then try to copy the things to remote host.
ssh -o StrictHostKeyChecking=no user#ip_addr
scp file_name user#ip_addr:/home/user

How to export credentials from one jenkins instance to another?

I am using the credentials plugin in Jenkins to manage credentials for git and database access for my team's builds. I would like to copy the credentials from one jenkins instance to another, independent jenkins instance. How would I go about doing this?
UPDATE: TL;DR Follow the link provided below in a comment by Filip Stachowiak it is the easiest way to do it. In case it doesn't work for you go on reading.
Copying the $HUDSON_HOME/credentials.xml is not the solution because Jenkins encrypts paswords and these can't be decrypted by another instance unless both share a common key.
So, either you use the same encription keys in both Jenkins instances (Where's the encryption key stored in Jenkins? ) or what you can do is:
Create the same user/password, you need to share, in the 2nd Jenkins instance so that a valid password is generated
What is really important is that user ids in both credentials.xml are the same. For that (see the credentials.xml example below) for user: Jenkins the identifier <id>c4855f57-5107-4b69-97fd-298e56a9977d</id> must be the same in both credentials.xml
<com.cloudbees.plugins.credentials.SystemCredentialsProvider plugin="credentials#1.22">
<domainCredentialsMap class="hudson.util.CopyOnWriteMap$Hash">
<entry>
<com.cloudbees.plugins.credentials.domains.Domain>
<specifications/>
</com.cloudbees.plugins.credentials.domains.Domain>
<java.util.concurrent.CopyOnWriteArrayList>
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
<scope>GLOBAL</scope>
<id>c4855f57-5107-4b69-97fd-298e56a9977d</id>
<description>Para SVN</description>
<username>jenkins</username>
<password>J1ztA2vSXHbm60k5PjLl5jg70ZooSFKF+kRAo08UVts=
</password>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
</java.util.concurrent.CopyOnWriteArrayList>
</entry>
</domainCredentialsMap>
</com.cloudbees.plugins.credentials.SystemCredentialsProvider>
I was also facing the same problem. What worked for me is I copied the credentials.xml, config.xml and the secrets folder from existing jenkins to the new instance. After the restart of jenkins things worked fine.
This is what worked for me.
Create a job in Jenkins that takes the credentials and writes them to output. If Jenkins replaces the password in the output with ****, just obfuscate it first (add a space between each character, reverse the characters, base64 encode it, etc.)
I used a Powershell job to base64 encode it:
[convert]::ToBase64String([text.encoding]::Default.GetBytes($mysecret))
And then used Powershell to convert the base64 string back to a regular string:
[text.encoding]::Default.GetString([convert]::FromBase64String("bXlzZWNyZXQ="))
After trying quite a few things for several days this is the best solution I found for migrating my secrets from a Jenkins 2.176 to a new clean Jenkins 2.249.1 jenkins-cli was the best approach for me.
The process is quite simple just dump the credentials from the old instance to a local machine, or Docker pod with java installed, as a XML file (unencrypted) and then uploaded to the new instance.
Before starting you should verify the following:
Access to the credentials section on both Jenkins instances
Download the jenkins-ccli.jar from one of the instances (https://www.your-jenkins-url.com/cli/)
Have User and Password/Token at hand.
Notice: In case your jenkins uses an oAuth service you will need to
create a token for your user. Once logged into jenkins at the top
right if you click your profile you can verify both username and
generate password.
Now for the special sauce, you have to execute both parts from the same machine/pod:
Notice: If your instances are using valid Certificates and you want to
secure your connection you must remove the -noCertificateCheck
flag from both commands.
# OLD JENKINS DUMP # 
export USER=madox#example.com
export TOKEN=f561banana6ead83b587a4a8799c12c307
export SERVER=https://old-jenkins-url.com/
java -jar jenkins-cli.jar -noCertificateCheck -s $SERVER -auth $USER:$TOKEN list-credentials-as-xml "system::system::jenkins" > /tmp/jenkins_credentials.xml
# NEW JENKINS IMPORT # 
export USER=admin
export TOKEN=admin
export SERVER=https://new-jenkins-url.com/
java -jar jenkins-cli.jar -noCertificateCheck -s $SERVER -auth $USER:$TOKEN import-credentials-as-xml "system::system::jenkins" < /tmp/jenkins_credentials.xml
If you have the credentials.xml available and the old Jenkins instance still running, there is a way to decrypt individual credentials so you can enter them in the new Jenkins instance via the UI.
The approach is described over at the DevOps stackexchange by kenorb.
This does not convert all the credentials for an easy, automated migration, but helps when you have only few credentials to migrate (manually).
To summarize, you visit the /script page over at the old Jenkins instance, and use the encrypted credential from the credentials.xml file in the following line:
println(hudson.util.Secret.decrypt("{EncryptedCredentialFromCredentialsXml=}"))
To migrate all credentials to a new server, from Jenkins: Migrating credentials:
Stop Jenkins on new server.
new-server # /etc/init.d/jenkins stop
Remove the identity.key.enc file on new server:
new-server # rm identity.key.enc
Copy secret* and credentials.xml to new server.
current-server # cd /var/lib/jenkins
current-server # tar czvf /tmp/credentials.tgz secret* credentials.xml
current-server # scp credentials.tgz $user#$new-server:/tmp/
new-server # cd /var/lib/jenkins
new-server # tar xzvf /tmp/credentials.tgz -C ./
Start Jenkins.
new-server # /etc/init.d/jenkins start
Migrating users from a Jenkins instance to another Jenkins on a new server -
I tried following https://stackoverflow.com/a/35603191 which lead to https://itsecureadmin.com/2018/03/26/jenkins-migrating-credentials/. However I did not succeed in following these steps.
Further, I experimented exporting /var/lib/jenkins/users (or {JENKINS_HOME}/users) directory to the new instance on new server. After restarting the Jenkins on new server - it looks like all the user credentials are available on new server.
Additionally, I cross-checked if the users can log in to the new Jenkins instance. It works for now.
PS: This code is for redhat servers
Old server:
cd /var/lib/jeknins
or cd into wherever your Jenkins home is
tar cvzf users.tgz ./users
New server:
cd /var/lib/jeknins
scp <user>#<oldserver>:/var/lib/jenkins/user.tgz ~/var/lib/jenkins/.
sudo tar xvzf users.tgz
systemctl restart jenkins
Did you try to copy the $JENKINS_HOME/users folder and the $JENKINS_HOME/credentials.xml file to the other Jenkins instance?

Jenkins Host key verification failed

I have a problem with jenkins, setting "git", shows the following error:
Failed to connect to repository : Command "git ls-remote -h https://person#bitbucket.org/person/projectmarket.git HEAD" returned status code 128:
stdout:
stderr: fatal: Authentication failed
I have tested with ssh:
git#bitbucket.org:person/projectmarket.git
This is error:
Failed to connect to repository : Command "git ls-remote -h git#bitbucket.org:person/projectmarket.git HEAD" returned status code 128:
stdout:
stderr: Host key verification failed.
fatal: The remote end hung up unexpectedly
I've also done these steps with "SSH key".
Login under Jenkins
sudo su jenkins
Copy your github key to Jenkins .ssh folder
cp ~/.ssh/id_rsa_github* /var/lib/jenkins/.ssh/
Rename the keys
mv id_rsa_github id_rsa
mv id_rsa_github.pub id_rsa.pub
but still not working git repository in jenkins.
thanks by help!.
Change to the jenkins user and run the command manually:
git ls-remote -h git#bitbucket.org:person/projectmarket.git HEAD
You will get the standard SSH warning when first connecting to a new host via SSH:
The authenticity of host 'bitbucket.org (207.223.240.181)' can't be established.
RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)?
Type yes and press Enter. The host key for bitbucket.org will now be added to the ~/.ssh/known_hosts file and you won't get this error in Jenkins anymore.
Jenkins is a service account, it doesn't have a shell by design. It is generally accepted that service accounts. shouldn't be able to log in interactively.
To resolve "Jenkins Host key verification failed", do the following steps. I have used mercurial with jenkins.
1)Execute following commands on terminal
$ sudo su -s /bin/bash jenkins
provide password
2)Generate public private key using the following command:
ssh-keygen
you can see output as ::
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
3)Press Enter --> Do not give any passphrase--> press enter
Key has been generated
4) go to --> cat /var/lib/jenkins/.ssh/id_rsa.pub
5) Copy key from id_rsa.pub
6)Exit from bash
7) ssh#yourrepository
8) vi .ssh/authorized_keys
9) Paste the key
10) exit
11)Manually login to mercurial server
Note: Pls do manually login otherwise jenkins will again give error "host verification failed"
12)once manually done, Now go to Jenkins and give build
Enjoy!!!
Good Luck
Or you can use:
ssh -oStrictHostKeyChecking=no host
This will be insecure (man in the middle attacks) but easiest solution.
The better way to do that is to generate correct mappings between host and ip address, so ssh will not complain:
#!/bin/bash
for domain in "github.com" "bitbucket.org"; do
sed -i "/$domain/d" ~/.ssh/known_hosts
line=$(ssh-keyscan $domain,`nslookup $domain | awk '/^Address: / { print $2 ; exit }'`)
echo $line >> ~/.ssh/known_hosts
done
Excerpt from gist.
I think, that many people didnt recognize, at least available since jenkins 2.361:
btw. No Verification is for sure not the best option.
Had same problem, i fix it like that :
reset permission on id_rsa* only for current user no group no other
chmod o-rwx ~/.ssh/id*
chmod G-rwx ~/.ssh/id*
ls -lart ~/.ssh/
-rw------- 1 jenkins nogroup 398 avril 3 09:34 id_rsa.pub
-rw------- 1 jenkins nogroup 1675 avril 3 09:34 id_rsa
And clear ~/.ssh/know_hosts
Now Connect as jenkins
sudo su jenkins
Try the jenkins commands
git ls-remote -h git#bitbucket.org:user/project.git HEAD
If no problem appears, now jenkins will be able to connect the repo (for me ^^ at least)
As for the workaround (e.g. Windows slave), define the following environment variable in global properties:
GIT_SSH_COMMAND="ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"
Note: If you don't see the option, you probably need EnvInject plugin for it.
login as jenkins using: "sudo su -s /bin/bash jenkins"
git clone the desired repo which causes the key error
it will ask you to add the key by showing Yes/No (enter yes or y)
that's it!
you can now re-run the jenkins job.
I hope you this will fix your issue.
using https://bitbucket.org/YYYY/XX.git
you shoud delete username#
Make sure we are not editing any of the default sshd_config properties to skip the error
Host Verification Failed - Definitely a missing entry of hostname in known_hosts file
Login to the server where the process is failing and do the following:
Sudo to the user running the process
ssh-copy-id destinationuser#destinationhostname
It will prompt like this for the first time, say yes and it will also ask password for the first time:
The authenticity of host 'sample.org (205.214.640.91)' can't be established.
RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)? *yes*
Password prompt ? give password
Now from the server where process is running, do ssh destinationuser#destinationhostname. It should login without a password.
Note: Do not change the default permissions of files in the user's .ssh directory, you will end up with different issues
I ran into this issue and it turned out the problem was that the jenkins service wasn't being run as the jenkins user. So running the commands as the jenkins user worked just fine.
Copy host keys from both bitbucket and github:
ssh root#deployserver 'echo "$(ssh-keyscan -t rsa,dsa bitbucket.org)" >> /root/.ssh/known_hosts'
ssh root#deployserver 'echo "$(ssh-keyscan -t rsa,dsa github.com)" >> /root/.ssh/known_hosts'
Best way you can just use your "git url" in 'https" URL format in the Jenkinsfile or wherever you want.
git url: 'https://github.com/jglick/simple-maven-project-with-tests.git'
SSH
If you are trying it with SSH, then the Host key Verification error can come due to several reasons.Follow these steps to overcome all the reasons.
Set the Environment variable as HOME and provide the address as the root directory of .ssh folder. e.g:- If your .ssh is kept inside Name folder.
C:/Users/Name.
Now make sure that the public SSH key is being provided in the repository link also. Either it is github or bitbucket or any other.
Open git bash. And try cloning the project from the repository. This will help in adding your repository URL in the known_host file, which is being auto created in the .ssh folder.
Now open jenkins and create a new job. Then click on configure.
provide the cloning URL in Source code management under Git. The URL should be start with git#github.com/......... or ssh://proje........
Under the Credential you need to add the username and password of your repository form which you are cloning the project. Select that credential.
And now apply and save the configuration.
Bingo! Start building the project. I hope now you will not get any Host Key verification error!
Try
ssh-keygen -R hostname
-R hostname Removes all keys belonging to hostname from a known_hosts file. This option is useful to delete hashed hosts
Use ssh-keyscan should be much more easier:
ssh-keyscan bitbucket.org >> ~/.ssh/known_hosts
This command will put all required hosts to ~/.ssh/known_hosts. You will need to run this command inside your Jenkins machine. You can also create a job and put that command into the "Execute shell" section of the Configure of that job and then execute the job.
issue is with the /var/lib/jenkins/.ssh/known_hosts. It exists in the first case, but not in the second one. This means you are running either on different system or the second case is somehow jailed in chroot or by other means separated from the rest of the filesystem (this is a good idea for running random code from jenkins).
Next steps are finding out how are the chroots for this user created and modify the known hosts inside this chroot. Or just go other ways of ignoring known hosts, such as ssh-keyscan, StrictHostKeyChecking=no or so.
After ssh-keygen probably one only needs to copy the public key to remote host with:
ssh-copy-id -i ~/.ssh/mykey user#host
There is a safe and (relative easy) way to accomplish this, which should also work if you have separate worker nodes/clouds (like docker/kubernetes).
Adding host keys to Jenkins configuration
First go to a console and execute ssh-keyscan your_git_server.url
Copy the output of that command
Then navigate to https://YOUR_JENKINS_URL/manage/configureSecurity/
Scroll down to Git Host Key Verification Configuration
Paste the output of the command into the window. it should look like this:
Both bitbucket and github have pages about their keys and servers. Read them and ensure that you are adding the proper keys and not some random keys
Getting the ssh-keyscan via your Jenkins installation
If you for some reason do not have ssh-keyscan, you can go to the script console ( https://YOUR_JENKINS_URL/manage/script ) and paste in the following script:
def sout = new StringBuilder(), serr = new StringBuilder()
def proc = 'ssh-keyscan bitbucket.org'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "copy this to jenkins>\n$sout"
//println "err> $serr"

Resources