java 通过JSch操作Linux

一 、需要的maven依赖

        
        com.jcraft
        jsch
        0.1.53
        
public class LinuxUtil {
//定义Linux 服务器的信息主机、用户、密码,端口这里采用默认端口。默认的ssh端口为22
    private static String host="192.168.xxx.xxx";
    private static String user="root";
    private static String pwd="xxxxxx";
//创建连接连接,这个方法调用后程序不会关闭,需要手动指定session.disconnect方法关闭连接
    public static Session connect(String host,String user,String pwd) throws JSchException {

        JSch jSch=new JSch();
//配置session连接参数
        Session session=jSch.getSession(user,host);
        session.setConfig("StrictHostKeyChecking","no");
        session.setPassword(pwd);
//开始连接
        session.connect();
        return session;
    }

//    执行Linux命令
    public static  void execSSh(Session session,String command) throws JSchException {
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        BufferedReader reader = null;
        try {
            channel.setCommand(command);
            channel.connect();
            channel.setErrStream(System.err);
//Linux执行的命令输出的结果会保存到channel里面,通过channel.getInputStream()方法获取
            InputStream in = channel.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in));
            String buf;
            List fileList = new ArrayList<>();
            while ((buf = reader.readLine()) != null) {
                fileList.add(buf.trim());
            }
//查看输出结果
            System.out.println("执行结果:"+ fileList);

        } catch (JSchException | IOException e) {
            throw new RuntimeException(e);
        }finally {
//关闭文件流
            if (reader != null) {
                reader.close();
            }
            if (channel!=null){
                channel.disconnect();
                session.disconnect();
            }
        }
    }

    public static void main(String[] args) throws JSchException {
        //例如查看redis进程
        String command="ps -ef | grep redis | grep -v grep";
        Session session=connect(host,user,pwd);
        execSSh(session,command);
        System.out.println("done!");
    }
}

你可能感兴趣的:(java,开发语言)