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

知识背景

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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值