Search code examples
jenkinssshjenkins-pipelinescp

Jenkins pipeline - scp command getting permission denied with sshagent


When using the sshagent wrapper, I'm able to ssh into server A and server B, but when using the scp command, I get permission denied

pipeline {
    agent {
        label 'pipeline'
    }
    
    stages {
        stage('SSH to remote host') {

            steps {
                sshagent(credentials: ['myCredentials']) {
                    sh '''
                        ssh [email protected] hostname -f
                        ssh [email protected] ls -l
                        
                        ssh [email protected] hostname -f
                        ssh [email protected] "echo 'hello world' >> thisFile.txt && ls -l"

                        scp [email protected]:~/thisFile.txt  [email protected]:~/thisFile.txt 
                     
                    '''
                }
            }
        }
    }
}

When running, the ssh commands return as expected, but the scp command chucks out the below

+ scp '[email protected]:~/thisFile.txt'  '[email protected]:~/thisFile.txt'
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

Solution

  • This is from the scp docs. Looks like scp tries to copy data b/w the remote hosts directly.

    1. We need to pass the -3 option.
     -3      Copies between two remote hosts are transferred through the
             local host.  Without this option the data is copied
             directly between the two remote hosts.  Note that, when
             using the legacy SCP protocol (via the -O flag), this
             option selects batch mode for the second host as scp cannot
             ask for passwords or passphrases for both hosts.  This mode
             is the default.
    
    1. We can use the -A option to forward the agent on the remote
     -A      Allows forwarding of ssh-agent(1) to the remote system.
             The default is not to forward an authentication agent.
    

    I have tried both of the above. Both seem to be working in my setup.