天天看点

java jsch shell_仅在JSch shell通道中获取特定命令的输出

我试图在使用JSch的java中获取shell脚本的输出。执行sudo管理命令并获取脚本的输出。仅在JSch shell通道中获取特定命令的输出

Properties prop = new Properties();

InputStream input = null;

String host="myhost";

StringBuilder command1= new StringBuilder();

String userName = "root";

String password="password";

try{

JSch jsch = new JSch();

Session session = jsch.getSession(userName, host, 22);

session.setPassword(password);

session.connect();

System.out.println("Connected");

List commands = new ArrayList();

commands.add("ls");

commands.add("sudo myadmincmd");

commands.add("cd /logs");

commands.add("my script...");

Channel channel = session.openChannel("shell");

channel.connect();

channel.setOutputStream(System.out);

OutputStream os = channel.getOutputStream();

PrintStream shell = new PrintStream(os, true);

for (String cmd : commands) {

shell.println(cmd);

try {

Thread.sleep(2000);

}

catch (Exception ee) {

}

}

shell.println("exit");

shell.close();

channel.disconnect();

session.disconnect();

}catch(Exception e){

e.printStackTrace();

}

输出:

*ADMINSHELL* :/home/abcd # cd /logs

*ADMINSHELL* :/logs #

*ADMINSHELL* :/logs # my script...

....

output goes here...

....

我怎样才能得到只有这ADMINSHELL的输出?例如,我只需要最终输出。我试着用下面的支票,

for (String cmd : commands) {

if(cmd.startsWith("for script")){

shell.println(cmd);

}

try {

Thread.sleep(2000);

}

catch (Exception e) {

}

}

但是这次我得到了一些权限被拒绝的问题。我只需要最后脚本的输出。

....

output goes here...

....

2016-08-11

NaaN