Java远程访问工具类

我们都知道,xshell、xftp等是远程访问的利器,但在实际工作中,有时要用java代码实现上面这2个工具的基础功能,远程访问和下载等等:

public class RemoteShellUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(RemoteShellUtil.class);

    private JSch jsch;

    private Session session = null;

    private String user = null;

    private String password = null;

    private String host = null;

    public void setUser(String user) {
        this.user = user;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void exec(String command) {
        if (this.session == null || !this.session.isConnected()) {
            if (!this.Connect(this.user, this.password, this.host)) {
                LOGGER.error("connect failed");
                return;
            }
        }

        BufferedReader reader = null;
        Channel channel = null;

        try {
            channel = this.session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);
            channel.setInputStream(null);
            int exitStatus = channel.getExitStatus();
            channel.connect();
            InputStream in = channel.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in));
            String buf;

            while ((buf = reader.readLine()) != null) {
                LOGGER.info(buf);
            }
        } catch (JSchException | IOException e) {
            LOGGER.error(Throwables.getStackTraceAsString(e));
        } finally {
            try {
                if (null != reader) reader.close();
                if (null != channel) channel.disconnect();
                this.session.disconnect();
            } catch (IOException e) {
                LOGGER.error(Throwables.getStackTraceAsString(e));
            }

        }

    }

    public Boolean download(String serverPath, String localpath) {
        if (!checkConnect()) return false;

        ChannelSftp channel = null;

        boolean status = false;
        try {
            channel = (ChannelSftp) this.session.openChannel("sftp");
            channel.connect();
            FileOutputStream out = new FileOutputStream(new File(localpath));
            BufferedOutputStream writer = new BufferedOutputStream(out);
            SftpProgressMonitor var10000 = new SftpProgressMonitor() {
                private long current = 0L;

                @Override
                public void init(int i, String s, String s1, long l) {
                }

                public boolean count(long arg0) {
                    this.current += arg0;
                    return true;
                }

                @Override
                public void end() {
                }
            };
            channel.get(serverPath, writer);
            writer.close();
            status = true;
        } catch (Exception e) {
            LOGGER.error(Throwables.getStackTraceAsString(e));
        } finally {
            if (null != channel) channel.disconnect();
            this.session.disconnect();
        }

        return status;
    }

    public Boolean upload(String serverPath, String localpath) {
        if (!checkConnect()) return false;

        ChannelSftp channel = null;

        boolean status = false;
        try {
            channel = (ChannelSftp) this.session.openChannel("sftp");
            channel.connect();
            FileInputStream in = new FileInputStream(new File(localpath));
            BufferedInputStream reader = new BufferedInputStream(in);
            SftpProgressMonitor var10000 = new SftpProgressMonitor() {
                private long current = 0L;

                public boolean count(long arg0) {
                    this.current += arg0;
                    return true;
                }

                public void end() {
                }

                public void init(int arg0, String arg1, String arg2, long arg3) {
                }
            };
            channel.put(reader, serverPath);
            reader.close();
            status = true;
        } catch (Exception e) {
            LOGGER.error(Throwables.getStackTraceAsString(e));
        } finally {
            if (null != channel) channel.disconnect();
            this.session.disconnect();
        }

        return status;
    }

    private Boolean Connect(String user, String password, String host) {
        try {
            if (null == this.jsch) this.jsch = new JSch();
            this.session = this.jsch.getSession(user, host, 22);
            this.session.setPassword(password);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            this.session.setConfig(config);
            this.session.connect();
            return true;
        } catch (Exception e) {
            LOGGER.error("connect failed, reason{}", Throwables.getStackTraceAsString(e));
            return false;
        }
    }

    private Boolean checkConnect() {
        if (this.session == null || !this.session.isConnected()) {
            return this.Connect(this.user, this.password, this.host);
        }
        return true;
    }
}

关注公众号“大模型全栈程序员”回复“小程序”获取1000个小程序打包源码。更多免费资源在http://www.gitweixin.com/?p=2627

发表评论

邮箱地址不会被公开。 必填项已用*标注