这是真真的问题任荣这是真正的问题内容 and卡洛斯你打算考能打上
您好,如果您想知道命令是否成功执行,可以通过判断返回值来确认,一般情况下返回0表示命令执行成功,其他值则表示执行失败。在这里可以将execute方法的返回值作为判断的依据,如果返回值为0,则说明命令执行成功,反之则失败。建议您对代码进行修改,加入相关的判断逻辑。另外,关闭端口的命令应该是"shutdown interface g 1/0/1",而不是"system-view\r\n interface g 1/0/1\r\n shutdown",请注意。
这里提供一种修改方式:
修改后的代码如下:
public synchronized boolean execute(String command){
int returnCode = 0;
JSch jsch = new JSch();
MyUserInfo userInfo = new MyUserInfo();
try{
//连接session
Session session = jsch.getSession(user, host, DEFAULT_SSH_PORT);
session.setPassword(pwd);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setUserInfo(userInfo);
session.connect();
//create and connect channel
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.connect();
System.out.println("The remote command is: " + command);
//Get the output of remote command
String line;
while((line = in.readLine())!= null){
stdout.add(line);
}
in.close();
//get the return code only after the channel is closed
if(channel.isClosed()){
returnCode = channel.getExitStatus();
}
//disconnect the channel and session
channel.disconnect();
session.disconnect();
//判断返回值
if(returnCode == 0){
return true; // 命令执行成功
}else{
return false; // 命令执行失败
}
}catch(JSchException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return false; // 命令执行失败
}
执行完成后,您可以根据返回值来判断命令的执行结果,如果为true则表示执行成功,反之则失败。