I am trying to execute commands remotely on a server under su
. Specifically, I am remotely executing:
su -c '[command]'
This works when I am logged into the remote server. My code to connect a session and run the command remotely looks something like this:
My question is hopefully pretty simple: How do I check if out.write
is replying to the password prompt provided in a su
command? Channels seem to be connected, and the program appears to work as long as su
is not involved.
Ideally the sequence for action is:
remote command initialized -> prompt for password -> input password remotely [failure point] -> execute command
It must be su
. It cannot be sudo
.
/**
* Method to connect to session.
*/
protected void connectSession(Session session){
try {
//connect to session and open exec channel
session.connect();
channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command); //set the command
((ChannelExec)channel).setPty(true); //set PTY tru for Password input
((ChannelExec)channel).setErrStream(System.err);
in = channel.getInputStream(); //set input stream
out=channel.getOutputStream(); //set output stream and connect
channel.connect();
System.out.println("Channel was connected");
out.write((sudo_pass+"\n").getBytes()); //write password upon prompt
out.flush();
//I believe the out.write and the out.flush section is not working. It probably breaks right before here.
System.out.println("Wrote sudo Pass");
} catch (JSchException | IOException e) {
System.out.println("Could not connect to session");
e.printStackTrace();
}
}
@Override
protected Integer RunCommand() throws Exception {
int j = 0;
System.out.println("Running command: " + command);
connectSession(session);
byte[] tmp=new byte[1024];
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}
catch(Exception ee){}
channel.disconnect();
}
I've borrowed heavily from:
- http://www.jcraft.com/jsch/examples/Sudo.java.html and
- https://sourceforge.net/p/jsch/mailman/message/25119880/
Hopes this helps anyone with similar problem!