Reputation: 31
I'm attempting to write some Java code that connects to a linux workstation, executes a command with sudo and then blocks until the command is complete.
session.getOutputStream().write("sudo -s \n".getBytes());
session.getOutputStream().write(command.getBytes());
session.getOutputStream().write("\n exit\n".getBytes());
IOStreamConnector output = new IOStreamConnector();
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
output.connect(session.getInputStream(), bos);
String theOutput = bos.toString();
doesn't seem to wait for the program to complete or return back the output.
session.executeCommand(command);
IOStreamConnector output = new IOStreamConnector();
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
output.connect(session.getInputStream(), bos);
session.getState().waitForState(ChannelState.CHANNEL_CLOSED);
theOutput = bos.toString();
Works well but not with sudo. I've tried setting the command:
"su -c \"touch /tmp/whatever\"" (touch is not the command I'm running, just using it to test.) This doesn't work.
"sudo touch /tmp/whatever" This doesn't work.
What is the magic formula for doing this???? Thanks in advance.
Upvotes: 0
Views: 203
Reputation: 1
I would suggest using something like this, works well for me:
if ( session.executeCommand("echo "+"/'your_sudo_password/' "+"| "+ "sudo -S "+command) ) {
IOStreamConnector output = new IOStreamConnector();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
output.connect(session.getInputStream(), bos );
session.getState().waitForState(ChannelState.CHANNEL_CLOSED);
theOutput = bos.toString();....
Upvotes: 0
Reputation: 510
Did you use the wait statement in the original 'startShell' based approach?
session.getState().waitForState(ChannelState.CHANNEL_CLOSED);
The code in the post appears to be attempting to capture the command output immediately after writing the sudo command. Since IOStreamConnector spawns threads to read the command it may not have completed before your session is closed.
Upvotes: 0