How to copy file from SSH remote host to Jenkins Server

后端 未结 3 685
长发绾君心
长发绾君心 2020-12-10 02:42

We are using Jenkins server for our daily build process and executes some bash scripts on remote hosts over SSH. This scripts are generating html log files on remote hosts.<

相关标签:
3条回答
  • 2020-12-10 02:50

    Obviously way too late, but in case you're already using publish-over-ssh, want to avoid duplicating the credentials and have a shared library you can use this piece of groovy to obtain the host configuration:

    import jenkins.plugins.publish_over_ssh.*
    
    @NonCPS
    def getSSHHost(name) {
      def found = null
      Jenkins.instance.getDescriptorByType(BapSshPublisherPlugin.Descriptor.class).each{
        it.hostConfigurations.each{host ->
          if (host.name == name) {
            found = host
          }
        }
      }
    
      found
    }
    

    As mentioned, this either requires a Global Shared Library (so that your code is trusted) or (probably) a number of admin approvals, sorry for that.

    This returns a BapSshHostConfiguration.

    For a password connection you can do:

    def sshHost = getSSHHost('Configuration Name')
    def host = [host: sshHost.hostname, user: sshHost.username, password: sshHost.password]
    sshHost = null
    sh("""
      set +x
      sshpass -p "${host.password}" scp -o StrictHostKeyChecking=no ${host.user}@${host.host}:filename.extension .
      set -x
    """)
    

    This copies the file to your local work directory. Probably not the best code ever, but I'm not a groovy specialist. It works and that is enough for me. (the set +x is to avoid it echoing the command in the log, showing the password). Getting rid of anything Non-CPS (sshHost = null) before you perform a CPS call saves you a lot of headaches :)

    Since it took me quite a while to figure out I wanted to share this for whoever comes next.

    0 讨论(0)
  • 2020-12-10 02:59

    I think you can generate ssh keypair and pass it to the slave as a parameter with, for example, Config File Provider Plugin

    Then just use scp to retrieve files using this keypair for authentication process.

    0 讨论(0)
  • 2020-12-10 03:08

    use sshpass command to send file in

    Build Environment -> Execute Shell script on remote host using ssh -> Post build script

    sample command :

    sshpass -p "password" scp path/of/file <new_server_ip>:/path/of/file
    

    This will skip password prompt for scp command and will provide password to scp.

    0 讨论(0)
提交回复
热议问题