1、创建 SFTP 用户
/**
* 新增SFTP用户
*
* @param tblSftpUser SFTP用户
* @return 结果
*/
@Override
public int insertTblSftpUser(TblSftpUser tblSftpUser) {
tblSftpUser.setCreateTime(DateUtilT.getNowDate());
tblSftpUser.setSftpPath(rootDir + tblSftpUser.getSftpUsername());
int row = tblSftpUserMapper.insertTblSftpUser(tblSftpUser);
if (row > 0) {
SFTPConfig config = new SFTPConfig();
config.setHost(host);
config.setPort(Integer.parseInt(port));
config.setUsername(username);
config.setPassword(password);
String sftpUser = tblSftpUser.getSftpUsername();
String sftpUserPwd = tblSftpUser.getSftpPassword();
String permission = tblSftpUser.getSftpPerms();
StringBuffer sb = new StringBuffer();
//1.创建SFTP用户
sb.append("useradd -g ").append(userGroup).append(" -s /usr/sbin/nologin ").append(sftpUser).append(";")
//2.修改密码
.append("echo ").append(sftpUser).append(":").append(sftpUserPwd).append(" | sudo chpasswd;")
//3.创建目录并授权
.append("mkdir -pm ").append(permission).append(" ").append(rootDir).append(sftpUser).append("/home");
ChannelExecUtils.getChannel(config, sb.toString());
}
return row;
}
public class ChannelExecUtils {
//等待时间,单位毫秒
private static final int TIMEOUT = 30000;
private static final Logger LOG = LoggerFactory.getLogger(ChannelExecUtils.class);
public static void getChannel(SFTPConfig sftpDetails, String command) {
String ftpHost = sftpDetails.getHost();
int ftpPort = sftpDetails.getPort();
String ftpUserName = sftpDetails.getUsername();
String ftpPassword = sftpDetails.getPassword();
Channel channel = null;
Session session = null;
try {
JSch jsch = new JSch(); // 创建JSch对象
session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根据用户名,主机ip,端口获取一个Session对象
if (ftpPassword != null) {
session.setPassword(ftpPassword); // 设置密码
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
config.put("PreferredAuthentications", "password");
config.put("X11Forwarding", "no");
session.setConfig(config); // 为Session对象设置properties
session.setTimeout(TIMEOUT); // 设置timeout时间
session.connect(); // 通过Session建立链接
channel = session.openChannel("exec"); // 打开执行shell指令通道
ChannelExec channelExec = (ChannelExec) channel;
channelExec.setCommand(command);
channel.setInputStream(null);
channelExec.setErrStream(System.err);
channel.connect(); // 建立执行shell指令通道的连接
LOG.debug("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName + ", command = " + command);
} catch (JSchException e) {
LOG.error("exec error :{}", e.getMessage(), e);
throw new UtilException("exec error");
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
}