karthik m
karthik m

Reputation: 5

How to make ssh connection in workflow through groovy script by using sand box in Jenkins?

How to make ssh connection in workflow through groovy script by using sand box in Jenkins? we need to make a ssh connection to a server and run particular script on that server with a particular user id..

is there any way to do that?

Upvotes: 0

Views: 9658

Answers (2)

Jesse Glick
Jesse Glick

Reputation: 25481

There is no trick.

sh 'ssh -u someone server some-script'

Upvotes: 2

Mark Fisher
Mark Fisher

Reputation: 9886

I had a similar requirement for our build system, and I started with this ssh.gradle task.

It comes down to using ant's sshexec as follows:

class SshTask extends DefaultTask {

    // various properties for the host etc
    @Input @Optional String host
    @Input @Optional String userName
    @Input @Optional String password
    @Input @Optional String keyfile
    @Input @Optional String passphrase

    private static boolean antInited = false

    SshTask() {
        if (!antInited) {
            antInited = true
            initAnt()
        }
    }

    protected initAnt() {
        project.configurations { sshAntTask }
        project.dependencies {
            sshAntTask "org.apache.ant:ant-jsch:1.8.2"
        }
        ant.taskdef(name: 'sshexec',
                classname: 'org.apache.tools.ant.taskdefs.optional.ssh.SSHExec',
                classpath: project.configurations.sshAntTask.asPath, loaderref: 'ssh')
    }

    def ssh(Object... commandLine) {
        def outputAntProperty = "sshoutput-" + System.currentTimeMillis()
        if (keyfile != null) {
            ant.sshexec(host: host, username: userName, keyfile: keyfile, passphrase: passphrase, command: commandLine.join(' '), outputproperty: "$outputAntProperty")
        } else if (password != null) {
            ant.sshexec(host: host, username: userName, password: password, command: commandLine.join(' '), outputproperty: "$outputAntProperty")
        } else {
            throw new GradleException("One of password or keyfile must be set to perform ssh command")
        }
        def sshoutput = ant.project.properties."$outputAntProperty"
        project.logger.lifecycle sshoutput
    }
}

Upvotes: 0

Related Questions