您的位置 首页 java

JSch神器:Java程序操控远程Linux主机实战

概述

JSch特别方便开发人员使用JAVA操作远程Linux主机,如重启、执行脚本、执行命令、并能够获取结果。JSch是一个SSH2的纯 Java 实现。JSch允许您连接到sshd服务器并使用端口转发、X11转发、文件传输等,您可以将其功能集成到自己的Java程序中。JSch使用 BSD 开源协议,该协议是一个给予使用者很大自由的协议,基本上等同于为所欲为:可以自由的使用、修改源代码、也可以将修改后的代码作为开源或者专有软件再发布。

pom文件

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

使用方法

只需实例化一个 Session ,就可以为所欲为的操作 Linux

实例化Session代码

 public static Session getSession(HostParams hostParams) throws JSchException {
    JSch jSch = new JSch();
    if (Files.exists(Paths.get(hostParams.getIdentity()))) {
        jSch.addIdentity(hostParams.getIdentity(), hostParams.getPassphrase());
    }

    Session session = jSch.getSession(hostParams.getUsr(), hostParams.getPwd(), hostParams.getSshPort());
    session.setPassword(hostParams.getPwd());

    Properties properties = new Properties();
    properties.put("StrictHostKeyChecking", "no");
    session.setConfig(properties);

    return session;
}  

操作远程Linux主机并获取返回结果

 public static List<String> rmtExec(Session session, String cmd) throws JSchException {
        List<String> resLines = new ArrayList<>();
        ChannelExec channel = null;
        try {
            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(cmd);
             InputStream  inputStream = channel.getInputStream();
            channel.connect(50_000);
            try {
                BufferedReader bufferedReader = new BufferedReader(new  inputStream Reader(inputStream));
                String inputLine;
                while ((inputLine = bufferedReader.readLine()) != null) {
                    System.out.println(inputLine);
                    resLines.add(inputLine);
                }
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch ( Exception  ex) {
                        ex.printStackTrace();
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (channel != null) {
                try {
                    channel.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return resLines;
    }  

案例演示

远程操作Linux主机,执行如下命令,获取结果:

 ls  /opt  

我们先看下远程Linux主机/opt下有什么内容:

通过JSch操作的结果​:

总结

​墙裂推荐JSch,你终会用到​,trust me!!

文章来源:智云一二三科技

文章标题:JSch神器:Java程序操控远程Linux主机实战

文章地址:https://www.zhihuclub.com/182548.shtml

关于作者: 智云科技

热门文章

网站地图