sftp没有关闭session导致服务器sshd进程未关闭

来源:互联网 发布:智慧与大数据考试答案 编辑:程序博客网 时间:2024/05/17 07:35

项目中需要用Sftp上传下载文件,通过jsch中的sftp实现。代码上了服务器之后,发觉服务器多了很多进程没有被关闭。
这里写图片描述
连接sftp代码:

 protected boolean connectToServer() {        try {            JSch jsch = new JSch();            jsch.getSession(userName, hostname, port);            Session sshSession = jsch.getSession(userName, hostname, port);            logger.debug("HostName:" + hostname + "|Port:" + port);            logger.debug("Session created");            sshSession.setPassword(password);            Properties sshConfig = new Properties();            sshConfig.put("StrictHostKeyChecking", "no");            sshSession.setConfig(sshConfig);            sshSession.setTimeout(TIMEOUT); //ms            sshSession.connect();            sftp = (ChannelSftp) sshSession.openChannel("sftp");            sftp.connect();            if (!sftp.isConnected()) {                logger.error("Failed to connect FTP server " + hostname);                return false;            }            logger.debug("Username:" + userName + "|Password:" + password);        } catch (Exception ex) {            logger.error(ex);        }        return true;    }

其实每次执行完都会

sftp.quit();
sftp.disconnet();

但是进程还是在,后来觉得应该是session没有关闭。后来证明的确是这样的,虽然sftp退出了,但是session还是存在的。解决办法很简单,只要在sftp.quit() 之前加上 sftp.getSession().disconnect() 就可以了。

0 0