This question already has an answer here:
jsch = new JSch();
session = jsch.getSession(userName, ip, 22);
session.setPassword(passWord);
session.connect();
channel = session.openChannel("shell");
expect = new Expect(channel.getInputStream(), channel.getOutputStream());
((ChannelShell) channel).setPtyType("dumb");
channel.connect();
System.out.println("After channel and expect");
if (expect.expect("#") > -1) {
output = "Connected";
} else {
output = "Unexpected Prompt";
System.out.println("Unexpected Prompt");
}
expect.send("top" + "\n");
Thread.sleep(3000);
System.out.println("inside top");
OutputStream out = channel.getOutputStream();
out.write(3); // send CTRL-C
out.flush();
System.out.println("exit1");
if (expect.expect("$") > -1) {
System.out.println("finding $");
contt = (expect.before);
if (contt != null && contt != "") {
output=StringUtils.replace(contt,"\"","");
System.out.println("afterline"+output);
} else {
contt="Error in Top Check";
System.out.println("Error in Top check");
}
} else {
System.out.println("oit");
}
While I am running this code, I am getting output
[H[J[mtop - 05:54:39 up 53 days, 15:21, 22 users, load average: 0.44, 0.80, 0.76[m[K
Tasks:[m[m 443 [mtotal,[m[m 1 [mrunning,[m[m 442 [msleeping,[m[m 0 [mstopped,[m[m 0 [mzombie[m[K
Cpu(s):[m[m 2.8%[mus,[m[m 0.8%[msy,[m[m 0.1%[mni,[m[m 95.9%[mid,[m[m 0.3%[mwa,[m
like these. I am getting unwanted characters along with it. How can I remove them?
These are ANSI escape codes that are normally interpreted by a terminal client to pretty print the output.
You get these, because you the JSch "shell" channel by default requests a pseudo terminal for the session. In general, its a bad idea to use a "shell" channel for automation.
But if you really have to for some reason, disable pseudo terminal by calling setPty
:
channel.setPty(false);
But in 99% cases it's a bad idea. Trying to simulate a human is error prone. The human-interaction features of commands tend to change (get improved), what in turn will break your code, when the server gets updated.
You better ask new question about your ultimate goal (what do you want to use top
for?), because you are likely on a wrong track.
Related questions:
来源:https://stackoverflow.com/questions/44276916/remove-of-unwanted-characters-when-i-am-using-jsch-to-run-command