SFTP 为 SSH的一部分。在SSH软件包中,已经包含了一个叫作SFTP(Secure File Transfer Protocol)的安全文件信息传输子系统,SFTP本身没有单独的守护进程,它必须使用sshd守护进程(端口号默认是22)来完成相应的连接和答复操作,所以从某种意义上来说,SFTP并不像一个服务器程序,而更像是一个客户端程序。SFTP同样是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。但是,由于这种传输方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。
groupadd sftp
useradd -g sftp -s /sbin/nologin -d /home/sftp/ftpuser1 ftpuser1
useradd -g sftp -s /sbin/nologin -d /home/sftp/ftpuser2 ftpuser2
passwd ftpuser1
passwd ftpuser1
mkdir /home/sftp/{ftpuser1,ftpuser1}
chown -R ftpuser1:sftp /home/sftp/ftpuser1
chown -R ftpuser2:sftp /home/sftp/ftpuser2
vi /etc/ssh/sshd_config
#Subsystem sftp /usr/libexec/openssh/sftp-server Subsystem sftp internal-sftp Match Group sftp #配置文件中有的配置项请注释掉 X11Forwarding no AllowTcpForwarding no ForceCommand internal-sftp ChrootDirectory /home/sftp/ 注意事项 /home/sftp/ 及以上到/目录的所有者必须为root /home/sftp/ /home/sftp/ftpuser1 /home/sftp/ftpuser2 不能有w权限 /home/sftp/ftpuser1 /home/sftp/ftpuser2 对应各自的用户才有put/get权限systemctl restart sshd
sftp ftpuser1@localhost
输入密码即可
上传
public static void upload(String uploadFile,String targetDirectory, ChannelSftp sftp) { try { sftp.cd(targetDirectory); File file = new File(uploadFile); if (file.exists()) { FileInputStream fis = new FileInputStream(file); sftp.put(fis, file.getName()); fis.close(); //删除文件 file.delete(); }else { System.out.println(file.getPath()); System.err.println("找不到要上传的文件!"); } } catch (Exception e) { System.err.println("上传文件出错!"); e.printStackTrace(); } }参考
https://yq.aliyun.com/articles/335854