问题
I have successfully SSH'ed into a node, sent the input, and retrieved the output. After inputting a line, the line is printed to the console, followed by a blank line, and then the output prints twice. I don't want the input to print to the console after it is entered, nor the blank line, nor the output printed a second time. Below is the code I have
public void runSession() {
try {
Channel channel = session.openChannel("shell");
channel.setInputStream(System.in, true);
channel.setOutputStream(System.out, true);
channel.connect(defaultChannelTimeout);
while (channel.getExitStatus() == -1) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
channel.disconnect();
} catch(JSchException jschEx) {
System.out.println("JSch exception during I/O");
System.out.println(jschEx.getMessage());
}
}
Here is what the console looks like when running
user:domain@node:/a/b/c> cd ..
cd ..
user:domain@node:/a/b> user:domain@node:/a/b>
As you can see, there are issues:
- The "cd.." is printed on a line to the console by itself
- A blank line appears after the "cd.."
- The "user:domain@node:/a/b>" line is printed twice.
Does anyone know how I can remove these 3 items from being displayed in the console? Desired output is
user:domain@node:/a/b/c> cd..
user:domain@node:/a/b>
回答1:
These are all consequences of the "shell" channel.
You run an interactive session with all the fancy stuff that human users like.
The "shell" channel is not intended for automation.
You may remove some of these by calling channel.setPty(false) before channel.connect().
Though you better use the "exec" channel.
This may work:
( echo username & echo password & echo hostname ) | command
Related questions:
- Remove of unwanted characters when I am using JSch to run command
- Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?
来源:https://stackoverflow.com/questions/40142559/removing-shell-stuff-like-prompts-from-command-output-in-jsch