Martin Pernollet
Martin Pernollet

Reputation: 2315

How to run a command requiring a password through SSH with Jsch

I am trying to use JSch to run a command on a target host, and I wish to be able to indicate a passphrase, for example: "sudo echo hello" and then enter the password for the current user.

I don't understand how to properly interact with the prompt. The code below shows two ways I tried to provide the password, they all fail with message:

sudo: no tty present and no askpass program specified

I am working with this:

JSch jsch=new JSch();
String host="192.168.0.17";
String user="xxx";
String passwd="xxx";

Session session=jsch.getSession(user, host, 22);
session.setPassword(passwd);
session.setConfig("StrictHostKeyChecking", "no"); 
session.connect();  

ChannelExec channel=(ChannelExec)session.openChannel("exec");
channel.setCommand("sudo echo hello");
channel.setErrStream(System.err);
channel.connect();


int id = 1;
// must write on output stream?
if(id==0){
channel.getOutputStream().write(passwd.getBytes());
}
// must read on input stream?
else if(id==1){
channel.getInputStream().read(passwd.getBytes());
}

channel.disconnect();

Thanks for your suggestions!

Upvotes: 4

Views: 5130

Answers (1)

ymnk
ymnk

Reputation: 1155

How about trying http://www.jcraft.com/jsch/examples/Sudo.java.html ?

Upvotes: 2

Related Questions