@Service
public class FileUP {
/**
* 加解密Key
*/
public static final String ENCODE_RULES = "xxxxxx";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Override
public boolean getServiceDetailed() {
Boolean result = null;
result = importData();
return result;
}
/**
* 生成CSV文件
*
* @return
*/
public boolean importData() {
Integer serverType = 2;
String filePath = "/SctrlClient/serviceDetailed";//上传文件至此路径
String fileName = "ServiceDeytailed";//文件名称
try {
//获取的要上传的数据
List<ServiceDetailedInfo> serviceDetailedList = detailedService.getServiceDetailed();
if (serviceDetailedList.size() > 0) {
Object[] head = { "Protocal", "Domain", "StartIP", "EndIP", "StartPort", "EndPort", "Command" };
List<Object> headList = Arrays.asList(head);// 设置表头
File csvFile = createCSVFile(serviceDetailedList, headList, fileName);
SysServerprcByType.saveDataToFileServerPcByType(csvFile, fileName + ".csv", filePath, serverType);
csvFile.delete();// 删除本地生成的临时文件
logger.info("服务器清单csv文件上传成功!");
} else {
logger.info("服务器清单csv文件上传失败!");
}
} catch (Exception e) {
logger.error("获取清单表失败!", e);
}
return true;
}
//生成要上传的csv文件
private File createCSVFile(List<ServiceDetailedInfo> serviceDetailedList, List<Object> headList, String fileName) {
File csvFile = null;
BufferedWriter csvWriter = null;
try {
// 定义文件格式并创建
csvFile = File.createTempFile(fileName, ".csv");
// UTF-8使正确读取分隔符“,”
csvWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"), 1024);
// 写入文件头部
writeHead(headList, csvWriter);
// 写入文件内容
// for (List<LogMeg> row : dataList) {
writeRow(serviceDetailedList, csvWriter);
// }
csvWriter.flush();
} catch (Exception e) {
logger.error("生成csv文件失败!!", e);
} finally {
try {
csvWriter.close();
} catch (Exception e) {
logger.error("关闭CSV文件写入流失败!!", e);
}
}
return csvFile;
}
/**
* 写一行数据方法(行内内容)
*
* @param exportData
* 导入的数据
* @param csvWriter
* 写入的数据
* @throws Exception
* 抛出异常
*/
private void writeRow(List<ServiceDetailedInfo> exportData, BufferedWriter csvWriter) throws Exception {
for (ServiceDetailedInfo data : exportData) {
StringBuffer sb = new StringBuffer();
sb.append("\"").append(data.getProtocal()).append("\"\t");
sb.append("\"").append(data.getDomain()).append("\"\t");
sb.append("\"").append(data.getStartIP()).append("\"\t");
sb.append("\"").append(data.getEndIP()).append("\"\t");
sb.append("\"").append(data.getStartPort()).append("\"\t");
sb.append("\"").append(data.getEndPort()).append("\"\t");
sb.append("\"").append(data.getCommand()).append("\"\t");
String rowStr = sb.toString();
// 加密后保存csv格式
String aesRowStr=SymmetricEncoder.AESEncode(ENCODE_RULES, rowStr);
csvWriter.write(aesRowStr);
csvWriter.newLine();
}
}
/**
*
* @param row
* 行
* @param csvWriter
* 写入的数据
* @throws Exception
* 抛出的异常
*/
private void writeHead(List<Object> headList, BufferedWriter csvWriter) throws Exception {
for (Object data : headList) {
StringBuffer sb = new StringBuffer();
sb.append("\"").append(data);
if (!data.equals("Command")) {
sb.append("\",").toString();
} else {
sb.append("\"");
}
// 加密后保存csv格式
String aesRowStr = SymmetricEncoder.AESEncode(ENCODE_RULES, sb.toString());
csvWriter.write(aesRowStr);
}
csvWriter.newLine();
}
@Override
public ResponseModel<List<ServiceInfo>> getServiceDetailedPath() {
ResponseModel<List<ServiceInfo>> returnValue=new ResponseModel<List<ServiceInfo>>();
try {
List<ServiceInfo> serviceInfoList=detailedService.getServiceDetailedPath();
returnValue.setData(serviceInfoList);
returnValue.setStatusCode(ResponseCode.SUCCESS);
} catch (Exception e) {
returnValue.setStatusCode(ResponseCode.ERROR);
returnValue.setMessage("获取服务器清单下载地址失败!");
logger.error("获取服务器清单下载地址失败!",e);
}
return returnValue;
}
}
=========================这里附上使用的工具类
import com.jcraft.jsch.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.InputStream;
import java.util.*;
/**
* 文件工具类.
* 1.所有的文件路径必须以'/'开头和结尾,否则路径最后一部分会被当做是文件名
* 2. @since version-0.3 方法出现异常的时候,<del>会关闭sftp连接(但是不会关闭session和channel)</del>(del @ version 0.31),异常会抛出
*
* @author Leon Lee
*/
public class SFTPUtil {
private final static Log log = LogFactory.getLog(SFTPUtil.class);
/**
* sftp连接池.
*/
private static final Map<String, Channel> SFTP_CHANNEL_POOL = new HashMap<String, Channel>();
/**
* 获取sftp协议连接.
*
* @param host 主机名
* @param port 端口
* @param username 用户名
* @param password 密码
* @return 连接对象
* @throws JSchException 异常
*/
public static ChannelSftp getSftpConnect(String ip, int port, String user, String password) throws JSchException {
Session sshSession = null;
Channel channel = null;
ChannelSftp sftp = null;
String key = ip + "," + port + "," + user + "," + password;
if (null == SFTP_CHANNEL_POOL.get(key)) {
sshSession = getSession(user, password, ip, port);
channel = sshSession.openChannel("sftp");
channel.connect();
SFTP_CHANNEL_POOL.put(key, channel);
} else {
channel = SFTP_CHANNEL_POOL.get(key);
sshSession = channel.getSession();
if (!sshSession.isConnected())
sshSession.connect();
if (!channel.isConnected())
channel.connect();
}
sftp = (ChannelSftp) channel;
return sftp;
}
private static Session getSession(String user, String passwd, String host,
int port) throws JSchException {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setConfig("userauth.gssapi-with-mic", "no");
session.setConfig("StrictHostKeyChecking", "no"); // 不验证host-key,验证会失败。
session.setPassword(passwd);
session.connect();
return session;
}
/**
* 删除文件-sftp协议.
*
* @param pathString 要删除的文件
* @param sftp sftp连接
* @throws SftpException 异常
*/
public static void rmFile(final String[] filePaths, final ChannelSftp sftp) throws SftpException {
for (String fileName : filePaths) {
if (dirExist(fileName, sftp)) {
sftp.rm(fileName);
}
}
}
public static void rmDir(List<String> filePaths, ChannelSftp sftp) throws SftpException {
for (String fileName : filePaths) {
if (dirExist(fileName, sftp)) {
sftp.rmdir(fileName);
}
}
}
/**
* 上传文件-sftp协议.
*
* @param srcFile 源文件
* @param dir 保存路径
* @param fileName 保存文件名
* @param sftp sftp连接
* @throws SftpException 异常
*/
public static void uploadFile(final String srcFile, final String dir, final List<String> fileNameList,
final List<ChannelSftp> sftps) throws SftpException {
for (ChannelSftp sftp : sftps) {
mkdir(dir, sftp);
sftp.cd(dir);
for (String fileName : fileNameList) {
sftp.put(srcFile, fileName);
}
}
}
/**
* 上传文件-sftp协议.
*
* @param srcFile 源文件
* @param dir 保存路径
* @param fileName 保存文件名
* @param sftp sftp连接
* @throws SftpException 异常
*/
public static void uploadFile(final String srcFile, final String dir, final String fileName, final ChannelSftp sftp)
throws SftpException {
mkdir(dir, sftp);
sftp.cd(dir);
sftp.put(srcFile, fileName);
}
/**
*
* @param ip sftp服务器ip
* @param port 端口
* @param user 用户名
* @param password 密码
* @param src 数据源
* @param dst 目的地
* @throws JSchException j
* @throws SftpException s
*/
public static void uploadFile(String ip, int port, String user, String password, String src, String dst) throws JSchException, SftpException {
ChannelSftp sftp = null;
Session session= null;
try {
session = getSftpSession(ip, port, user, password);
sftp = getSftpClient(session);
sftp.put(src, dst);
}
finally {
close(sftp, session);
}
}
/**
* 获取sftp连接
* @param ip sftp服务器ip
* @param port 端口
* @param user 用户名
* @param password 密码
* @return Session
* @throws JSchException e
*/
private static Session getSftpSession(String ip, int port, String user,String password) throws JSchException {
JSch jsch = new JSch();// 创建JSch对象
Session session = jsch.getSession(user, ip, port); // 根据用户名,主机ip,端口获取一个Session对象
session.setPassword(password); // 设置密码
session.setConfig("StrictHostKeyChecking", "no"); // 不验证host-key,验证会失败。
session.connect(); // 通过Session建立链接
return session;
}
/**
* 获取 ChannelSftp
* @param session session
* @return ChannelSftp
* @throws JSchException e
*/
private static ChannelSftp getSftpClient(Session session) throws JSchException {
Channel channel = session.openChannel("sftp");
channel.connect();
return (ChannelSftp) channel;
}
/**
* 关闭连接
* @param channel channel
* @param session session
*/
private static void close(Channel channel, Session session){
if (null != channel) channel.disconnect();
if (null != session) session.disconnect();
}
/**
* 根据路径创建文件夹.
*
* @param dir 路径 必须是 /xxx/xxx/ 不能就单独一个/
* @param sftp sftp连接
* @throws SftpException 异常
*/
public static boolean mkdir(final String dir, final ChannelSftp sftp) throws SftpException {
if (StringUtils.isBlank(dir))
return false;
String md = dir.replaceAll("\\\\", "/");
if (md.indexOf("/") != 0 || md.length() == 1)
return false;
return mkdirs(md, sftp);
}
/**
* 递归创建文件夹.
*
* @param dir 路径
* @param sftp sftp连接
* @return 是否创建成功
* @throws SftpException 异常
*/
private static boolean mkdirs(final String dir, final ChannelSftp sftp) throws SftpException {
String dirs = dir.substring(1, dir.length());
String[] dirArr = dirs.split("/");
String base = "";
for (String d : dirArr) {
base += "/" + d;
if (dirExist(base, sftp)) {
continue;
} else {
sftp.mkdir(base + "/");
}
}
return true;
}
/**
* 判断文件夹是否存在.
*
* @param dir 文件夹路径, /xxx/xxx/
* @param sftp sftp协议
* @return 是否存在
*/
private static boolean dirExist(final String dir, final ChannelSftp sftp) {
try {
Vector<?> vector = sftp.ls(dir);
if (null == vector)
return false;
else
return true;
} catch (SftpException e) {
return false;
}
}
/**
* 关闭协议-sftp协议.(关闭会导致连接池异常,因此不建议用户自定义关闭)
*
* @param sftp sftp连接
*/
public static void exit(final ChannelSftp sftp) {
sftp.exit();
}
}
======还有一个加密的工具类
import org.apache.log4j.Logger;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
public class AESUtils {
private static final Logger logger = Logger.getLogger(AESUtils .class);
/**
* AES加密
*/
public static String AESEncode(String seed, String cleartext) {
byte[] rawKey = new byte[0];
try {
rawKey = seed.getBytes();//getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
String hex= toHex(result);
Integer vlen=cleartext.length()>16?16- (cleartext.length()%16) :16-cleartext.length();
hex+=Integer.toHexString(vlen).toUpperCase();
return hex;
} catch (Exception e) {
logger.error("",e);
}
return null;
}
/**
* AES解密
*/
public static String AESDncode(String seed, String encrypted) {
try {
byte[] rawKey = seed.getBytes();//getRawKey()
encrypted=encrypted.substring(0, encrypted.length()-1);
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
} catch (Exception e) {
logger.error("",e);
}
return null;
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
/* SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;*/
SecretKeySpec key = new SecretKeySpec(raw, "AES");
// 加密
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(clear);
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
/*SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;*/
// 处理密钥
SecretKeySpec key = new SecretKeySpec(raw, "AES");
// 解密
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(encrypted);
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
}