1、maven依赖
com.jcraft
jsch
0.1.54
2、方法
private static void executeCommand(String userName, String IP, String password, String command) throws JSchException, IOException {
JSch jsch = new JSch();
Session e = jsch.getSession(userName, IP, 22);
e.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
e.setConfig(config);
e.connect();
Channel channel = e.openChannel("exec");
ChannelExec channelExec = (ChannelExec)channel;
channelExec.setCommand(command);
channelExec.setInputStream((InputStream)null);
BufferedReader input = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
channelExec.connect();
String line;
while((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
if(channelExec.isClosed()) {
int exitStatus = channelExec.getExitStatus();
System.out.println("exitCode="+exitStatus);
}
channelExec.disconnect();
e.disconnect();
}