centos7 sftp多用户配置与java客户端连接

xiaoxiao2021-02-28  51

知识背景

SFTP 为 SSH的一部分。在SSH软件包中,已经包含了一个叫作SFTP(Secure File Transfer Protocol)的安全文件信息传输子系统,SFTP本身没有单独的守护进程,它必须使用sshd守护进程(端口号默认是22)来完成相应的连接和答复操作,所以从某种意义上来说,SFTP并不像一个服务器程序,而更像是一个客户端程序。SFTP同样是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。但是,由于这种传输方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。

centos7配置sftp多用户

1,添加用户组和用户

groupadd sftp

useradd -g sftp -s /sbin/nologin -d /home/sftp/ftpuser1 ftpuser1

useradd -g sftp -s /sbin/nologin -d /home/sftp/ftpuser2 ftpuser2

2,修改密码

passwd ftpuser1

passwd ftpuser1

3,创建文件名录,修改mod

mkdir /home/sftp/{ftpuser1,ftpuser1}

chown -R ftpuser1:sftp /home/sftp/ftpuser1

chown -R ftpuser2:sftp /home/sftp/ftpuser2

4,修改sshd_config

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权限

5,重启sshd

systemctl restart sshd

6,登陆sftp

sftp ftpuser1@localhost

输入密码即可

java客户端连接

连接

public static ChannelSftp connect(String host, int port, String username, String password) throws JSchException { JSch jsch = new JSch(); Session sshSession = jsch.getSession(username, host, port); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); Channel channel = sshSession.openChannel("sftp"); channel.connect(); ChannelSftp sftp = (ChannelSftp) channel; logger.info("Connected to " + host + "."); return sftp; }

上传

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

转载请注明原文地址: https://www.6miu.com/read-2624336.html

最新回复(0)