码迷,mamicode.com
首页 > 编程语言 > 详细

java通过Linux获取命令信息并显示出来

时间:2018-08-06 15:20:40      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:缓存   sch   通过   username   script   try   desc   uptime   main   

代码如下:
package test;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @author lw
 * @createTime 2018/8/3 15:49
 * @description ssh登陆主机 输入密码登陆并执行命令
 */
public class LinuxShh {

    private static Logger logger = LogManager.getLogger(LinuxShh.class);

    final static String userName = "test";// 用户名
    final static String password = "87654321";// 密码
    final static String host = "174.31.514.222";// 服务器地址
    final static int port = 22;// 端口号
    final static int timeout = 60000000;

    /**
     * <dependency>
     * <groupId>com.jcraft</groupId>
     * <artifactId>jsch</artifactId>
     * <version>0.1.54</version>
     * </dependency>
     */
    public static void main(String[] args)  {
        String cmd = "uname -a && date && uptime && who && vmstat 1 60 ";
        /*try {

            String rs =   LinuxShh.exeCommand(host,port,userName,password,cmd);
            System.out.println(rs);

        } catch (JSchException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        try {
            LinuxShh.getLog(host,port,userName,password,cmd);
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
    *@Author:lw
    *@Description:  实时获取命令日志
     * @param :host,port user,password cmmmand
    *@Date:14:00 2018/8/6
    */
    public static void getLog(String host, int port, String user, String password, String command)throws JSchException, IOException{

        JSch jsch = new JSch(); // 创建JSch对象
        //String cmd = "vmstat 1 1";// 要运行的命
        String cmd = "uname -a && date && uptime && vmstat 1 60 ";  //>/home/linux_shell/m/vmstat.txt
        Session session = jsch.getSession(user, host, port); // 根据用户名,主机ip,端口获取一个Session对象
        session.setPassword(password); // 设置密码
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 为Session对象设置properties
        session.setTimeout(timeout); // 设置timeout时间
        session.connect(); // 通过Session建立链接
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        channelExec.setCommand(command);
        channelExec.setInputStream(null);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        InputStream in = channelExec.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
        //写入相应的文件
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:\\2.txt"),"UTF-8"));
        String buf = null;

        StringBuffer sb = new StringBuffer();

        System.out.println("您的IP是:" + host);
        logger.info("您的IP是:" + host);
        System.out.println("以下是:系统资源信息:");

        while ((buf = reader.readLine()) != null) {

            sb.append(buf);
            //写入相关文件
            out.write(buf);
            out.newLine();
            System.out.println(buf);// 打印控制台输出
        }
        //清楚缓存
        out.flush();
        //关闭流
        reader.close();
        out.close();
        channelExec.disconnect();
        if (null != session) {
            session.disconnect();
        }

    }

    /**
    *@Author:lw
    *@Description:  去除全部结果后,才显示处理,不是实时获取数据
    *@Date:13:53 2018/8/6
    */
    public static String exeCommand(String host, int port, String user, String password, String command) throws JSchException, IOException {

        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();
        session.setTimeout(timeout); // 设置timeout时间
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand(command);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        String out = IOUtils.toString(in, "UTF-8");
        channelExec.disconnect();
        session.disconnect();
        return out;
    }

}

结果:

技术分享图片

java通过Linux获取命令信息并显示出来

标签:缓存   sch   通过   username   script   try   desc   uptime   main   

原文地址:http://blog.51cto.com/357712148/2155239

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!