执行远程系统的操作系统命令
package javaoperation;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
/**
*
* @auther keven
* @date 2018/12/7 14:55
* @desc
* @since V1.0
*/
public class RemoteCommandUtil {
public static void main(String[] args) throws Exception {
JSch jsch = new JSch();
String userName = "root";
String password = "*";
String host = "10.11.13.*";
int port = 22;
String cmd = "netstat -ntlp";
//String cmd2 = "mkdir -p /software/test";
//String cmd3 = "ls /software";
Session session = jsch.getSession(userName, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
int timeout = 60000000;
session.setTimeout(timeout);
session.connect();
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand(cmd);
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
channelExec.connect();
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
String buf = null;
StringBuffer sb = new StringBuffer();
while ((buf = reader.readLine()) != null) {
sb.append(buf);
System.out.println(buf);
}
reader.close();
channelExec.disconnect();
if (null != session) {
session.disconnect();
}
}
}