Java代码执行Shell脚本指令

1、maven依赖

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>

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();
}

猜你喜欢

转载自my.oschina.net/u/1159254/blog/1593670
今日推荐