trivunm trivunm - 3 months ago 28
Java Question

Ganymed ssh2 : how to solve (y/n) prompt in command line

I'm using Ganymede ssh2 to connect to server from my Java app and do some work there.

It works perfectly but problems are ssh commands that request approval, eg.
a command

stop someService


returns

Are you sure (y/n)?


and after appropriate key stroke (y/n) it moves on.

Currently I'm using implementation given by ssh2 ganymed example, smth like this:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class ConnectUtil(String hostname, String username, String password, String command)
{

try
{
Connection conn = new Connection(hostname);
conn.connect();

boolean isAuthenticated = conn.authenticateWithPassword(username, password);

if (isAuthenticated == false)
throw new IOException("Authentication failed.");

Session sess = conn.openSession();

sess.execCommand(command);

InputStream stdout = new StreamGobbler(sess.getStdout());

BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
sess.close();
conn.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
}
}


After calling this util class with above mentioned command('stop someService'), it gets stucked at

String line = br.readLine();


and everything breaks after server timeout.

Any ideas on how to solve this issue are more than welcome.

Thanks a lot,
Milos.

Answer

Assuming Session has a getStdin() method, you should write the response to the question to that.

Either that or find out if the command that's demanding input has a 'non-interactive' mode that won't prompt.