java执行linux命令

作者 : 开心源码 本文共1491个字,预计阅读时间需要4分钟 发布时间: 2022-05-12 共289人阅读

废话不多说,直接上代码

package com.mlchain.strategy.utils;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 远程执行linux服务器*@since V1.0*/public class RemoteCommandUtil {    public static void main(String[] args) throws Exception {        JSch jsch = new JSch(); // 创立JSch对象        String userName = "####";// 客户名        String password = "####";// 密码        String host = "####";// 服务器地址        int port = 22;// 端口号        //String cmd = "cat /data/hello.txt";// 要运行的命令        String cmd = "netstat -ntlp";// 要运行的命令        Session session = jsch.getSession(userName, host, port); // 根据客户名,主机ip,端口获取一个Session对象        session.setPassword(password); // 设置密码        Properties config = new Properties();        config.put("StrictHostKeyChecking", "no");        session.setConfig(config); // 为Session对象设置properties        int timeout = 60000000;        session.setTimeout(timeout); // 设置timeout时间        session.connect(); // 通过Session建立链接        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();        }    }}

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » java执行linux命令

发表回复