Xeon
Xeon

Reputation: 5989

Groovy - execute ssh and provide password

I know that there are AntBuilder and JSch, etc. but I want do something like this - without any dependencies:

def sshArray = ["ssh [email protected] -p 111 '/etc/init.d/tomcat7 stop'", ...]

def env = System.getenv().collect { k,v -> "$k=$v" }

sshArray.each {
    println "Executing: " + it
    def process = (it).execute(env, null)
    def writer = new PrintWriter(new BufferedOutputStream(process.out))
    writer.println("mypassword")
    writer.close()
    process.waitFor()
    process.consumeProcessOutput(System.out, System.err)
}

But this sadly doesn't work, because the output I'm getting is:

Executing: ssh [email protected] -p 111 '/etc/init.d/tomcat7 stop'
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password).
...

Moreover, I'm getting the same output if I comment out these lines:

def writer = new PrintWriter(new BufferedOutputStream(process.out))
writer.println("mypassword")
writer.close()

Why am I getting "Permission denied" 3 times? How can I provide password to ssh process? Is this possible?

Upvotes: 0

Views: 5412

Answers (2)

Chris
Chris

Reputation: 1171

Sorry, but I think what you're doing is starting a process and then CONSUMING its output (process.out). You should be feeding the input to the process. It should be the InputStream you're dealing with.

Upvotes: 0

ataylor
ataylor

Reputation: 66099

Programs like ssh generally don't read the password from their standard input; they read it directly from the terminal. Java and groovy don't provide any way control the terminal.

This isn't a problem with ssh or Java: passwords are meant to be entered by a person. If your program needs to use ssh, the proper way to use it is with key-based authentication.

Upvotes: 4

Related Questions