|
2019-05-17
yum -y install vsftpd
sudo apt-get install vsftpd
[root@izwz94danzl2zfjfo5qll6z ~]# cat /etc/vsftpd/vsftpd.conf | grep -v "#" anonymous_enable=NO local_enable=YES write_enable=YES local_umask=022 dirmessage_enable=YES xferlog_enable=YES connect_from_port_20=YES xferlog_file=/var/log/xferlog xferlog_std_format=YES chroot_local_user=YES chroot_list_enable=NO listen=NO listen_ipv6=YES pam_service_name=vsftpd userlist_enable=YES tcp_wrappers=YES ssl_ciphers=HIGH rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key ssl_enable=NO
查看防火墙状态
getsebool -a | grep ftp
setsebool ftpd_full_access on
将
Subsystem sftp /usr/lib/openssh/sftp-server
替换为
Subsystem sftp internal-sftp
根据协议开放对应的端口
useradd -d /home/ftpuser ftpuser
passwrd ftpuser
chown -R ftpuser /home/ftpuser/
注意点:
建立连接
protected SftpConnect getConnect() throws Exception { Session session ; Channel channel ; ChannelSftp sftp ;// sftp操作类 JSch jsch = new JSch(); session = jsch.getSession(username, hostname, port); session.setPassword(password); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey session.setConfig(config); try { session.connect(); } catch (Exception e) { if (session.isConnected()) session.disconnect(); log.error("连接服务器失败,请检查主机[" + hostname + "],端口[" + port + "],用户名[" + username + "],端口[" + port + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝."); } channel = session.openChannel("sftp"); try { channel.connect(); } catch (Exception e) { if (channel.isConnected()) channel.disconnect(); log.error("连接服务器失败,请检查主机[" + hostname + "],端口[" + port + "],用户名[" + username + "],密码是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝."); } sftp = (ChannelSftp) channel; return SftpConnect.builder() .channel(channel) .session(session) .sftp(sftp) .build(); }
上传文件
public void upload(InputStream inputStream, String pathname, String fileName) throws Exception { SftpConnect connect = this.getConnect(); ChannelSftp sftp = connect.getSftp();// sftp操作类 try { sftp.cd(pathname); sftp.put(inputStream,fileName); } catch (Exception e) { log.error("JSchProxy.upload occur error;pathname={},fileName={}",pathname,fileName,e); throw CsdRuntimeException.of(ProxyEntityError.UPLOAD_FILE_ERROR); } finally { IOUtils.closeQuietly(inputStream); this.disConnect(connect); } }
读取数据
public byte[] readFromSftp(String pathname,String filename) throws Exception { SftpConnect connect = this.getConnect(); ChannelSftp sftp = connect.getSftp();// sftp操作类 byte[] buffer; InputStream inputStream = null ; try { Vector<ChannelSftp.LsEntry> sftpFile = new Vector(); sftp.ls(pathname, entry -> { if(entry.getFilename().contains(filename)) { log.info("readFromSftp find match file;fileName={}",filename); sftpFile.add(entry); return ChannelSftp.LsEntrySelector.BREAK; } return ChannelSftp.LsEntrySelector.CONTINUE; }); if(CollectionUtil.isEmpty(sftpFile)) { log.warn("JSchProxy.readFromSftp occur not find target file;pathname={},fileName={}",pathname,filename); return null; } sftp.cd(pathname); //进入目录 inputStream = sftp.get(sftpFile.get(0).getFilename()); buffer = new byte[inputStream.available()]; int read = inputStream.read(buffer); } catch (Exception e) { log.error("JSchProxy.upload readFromSftp error;pathname={},fileName={}",pathname,filename,e); throw CsdRuntimeException.of(ProxyEntityError.UPLOAD_FILE_ERROR); } finally { IOUtils.closeQuietly(inputStream); this.disConnect(connect); } return buffer; }
关闭资源
protected void disConnect(SftpConnect connect){ if(null == connect) { return; } ChannelSftp sftp = connect.getSftp(); if(null != sftp){ sftp.disconnect(); sftp.exit(); } Channel channel = connect.getChannel(); if(null != channel){ channel.disconnect(); } Session session = connect.getSession(); if(null != session){ session.disconnect(); } connect = null;//for gc }
建立连接
protected FTPSClient initFtpsClient() throws IOException { FTPSClient ftpsClient = new FTPSClient(); ftpsClient.setControlEncoding("UTF-8"); log.info("connecting...ftps服务器:" + this.hostname + ":" + this.port); ftpsClient.connect(hostname, port); // 连接ftps服务器 boolean loginRs = ftpsClient.login(username, password); // 登录ftps服务器 log.info("login...ftps服务器;loginRs={},username={},password={}",loginRs,username,password); ftpsClient.execPBSZ(0); ftpsClient.execPROT("P"); int replyCode = ftpsClient.getReplyCode(); // 是否成功登录服务器 if (!FTPReply.isPositiveCompletion(replyCode)) { log.info("connect failed...hostname={},port={},replyCode={}",this.hostname, this.port,replyCode); } log.info("connect successful...ftps服务器:" + this.hostname + ":" + this.port); ftpsClient.setDataTimeout(100000); //设置传输超时时间为60秒 ftpsClient.setConnectTimeout(100000); return ftpsClient; }
上传文件
public void upload(InputStream inputStream, String pathname, String fileName) { FTPSClient client = null; try { client = this.initFtpsClient(); if(null == client) { throw CsdRuntimeException.of(ProxyEntityError.CONNECT_FTP_ERROR); } client.enterLocalPassiveMode(); client.setFileType(FTP.BINARY_FILE_TYPE); //String[] rt=client.doCommandAsStrings("pwd",""); //log.info("current work dir is:{}", JSON.toJSONString(rt)); client.changeWorkingDirectory(pathname); boolean uploadRs = client.storeFile(fileName,inputStream); log.info("FtpsClientProxy.upload rs={},pathname={},fileName={}",uploadRs,pathname,fileName); int replyCode = client.getReplyCode(); log.info("FtpsClientProxy.upload replyCode={},pathname={},fileName={}",replyCode,pathname,fileName); client.logout(); } catch (ConnectException e) { log.error("FtpsClientProxy.upload occur error;pathname={},fileName={}",pathname,fileName,e); throw CsdRuntimeException.of(ProxyEntityError.CONNECT_EXCEPTION); } catch (IOException e) { log.error("FtpsClientProxy.upload occur error;pathname={},fileName={}",pathname,fileName,e); throw CsdRuntimeException.of(ProxyEntityError.UPLOAD_FILE_ERROR); } catch (CsdRuntimeException e) { log.error("FtpsClientProxy.upload occur error;pathname={},fileName={}",pathname,fileName,e); throw e; } catch (Exception e) { log.error("FtpsClientProxy.upload occur error;pathname={},fileName={}",pathname,fileName,e); throw CsdRuntimeException.of(ProxyEntityError.SYSTEM_ERROR); } finally { IOUtils.closeQuietly(inputStream); this.disconnect(client); } }
读取数据
public byte[] readFromSftp(String pathname,FTPFileFilter filter) { FTPSClient client = null; byte[] buffer; InputStream inputStream = null; try { client = this.initFtpsClient(); if(null == client) { throw CsdRuntimeException.of(ProxyEntityError.CONNECT_FTP_ERROR); } client.enterLocalPassiveMode(); client.type(FTP.BINARY_FILE_TYPE); //client.setFileType(FTP.BINARY_FILE_TYPE); FTPFile[] ftpFiles = client.listFiles(pathname, filter); //暂且认为只有一个符合条件的文件 if(null == ftpFiles || ftpFiles.length == 0) { //Alarm.report("Csd find no extensya uploaded file to download..."); throw CsdRuntimeException.of(ProxyEntityError.NO_FILE_FIND); } client.changeWorkingDirectory(pathname); inputStream = client.retrieveFileStream(ftpFiles[0].getName()); buffer = ByteStreams.toByteArray(inputStream); client.logout(); } catch (IOException e) { log.error("FtpsClientProxy.readExcel occur error;pathname={}",pathname,e); throw CsdRuntimeException.of(ProxyEntityError.UPLOAD_FILE_ERROR); } catch (CsdRuntimeException e) { log.error("FtpsClientProxy.readExcel occur error;pathname={}",pathname,e); throw e; } catch (Exception e) { log.error("FtpsClientProxy.readExcel occur error;pathname={}",pathname,e); throw CsdRuntimeException.of(ProxyEntityError.SYSTEM_ERROR); } finally { IOUtils.closeQuietly(inputStream); this.disconnect(client); } return buffer; }
关闭资源
protected void disconnect(FTPSClient ftpsClient) { if(null == ftpsClient) { log.warn("FtpsClientProxy.disconnect client is null"); return; } if(!ftpsClient.isConnected()) { log.warn("FtpsClientProxy.disconnect client is closed;connected = {}",ftpsClient.isConnected()); return; } try { ftpsClient.disconnect(); } catch (IOException e) { log.error("FtpsClientProxy.disconnect occur error;",e); } }
编辑:航网科技 来源:腾讯云 本文版权归原作者所有 转载请注明出处
微信扫一扫咨询客服
全国免费服务热线
0755-36300002