您的位置:首页 > 编程语言 > PHP开发

sftp 上传日志

2016-03-25 10:23 701 查看
log 操作:

————————————————————————————————

LogUploadingSftp.java

package com.nari.misp.webservice.modules.isc.quartz;

import java.io.File;

import java.io.FileWriter;

import java.text.ParseException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import java.util.logging.Logger;

import com.jcraft.jsch.ChannelSftp;

import com.nari.misp.common.utils.DateUtils;

import com.nari.misp.common.utils.FileUtils;

import com.nari.misp.common.utils.SpringContextHolder;

import com.nari.misp.modules.sys.dao.LogDao;

import com.nari.misp.modules.sys.entity.Log;

import com.nari.misp.modules.sys.utils.IscSSOInfoUtil;

import com.nari.misp.webservice.modules.isc.SFTPHandle;

public class LogUploadingSftp {

private LogDao logDao = SpringContextHolder.getBean(LogDao.class);
private static final Logger LOG = Logger.getLogger(LogUploadingSftp.class
.getName());

private LogUploadingSftp() {
}

private static LogUploadingSftp single = null;
@SuppressWarnings("static-access")
private static Map<String, String> logsftpMap = IscSSOInfoUtil
.getInstance().getAllConfig();

// 静态工厂方法
public static synchronized LogUploadingSftp getInstance() {
if (single == null) {
single = new LogUploadingSftp();
}
return single;
}

/**
* 上传本系统日志文件到4asft服务器
*/
@SuppressWarnings("static-access")
public void uploadLog() {
// 上传的日志列表
List<Log> listLog = this.allList();
if (null != listLog) {
// 转换Log对象为字符串
List<String> listStr = this.logToString(listLog);
// 写入临时文件
String filepath = logsftpMap.get("ims.log.temp.path")
+ File.separator;
String fileName = filepath + DateUtils.getDate("yyyyMMdd")
+ logsftpMap.get("isc.sso.log.file.suffix");

if (this.createFile(fileName)) {
// 写入文件
this.writeFailures(fileName, listStr);
// 上传文件sft
SFTPHandle sf = new SFTPHandle();
String host = logsftpMap.get("isc.sso.log.sftp.adder");
int port = Integer.parseInt(logsftpMap
.get("isc.sso.log.sftp.post"));
String username = logsftpMap.get("isc.sso.log.sftp.username");
String password = logsftpMap.get("isc.sso.log.sftp.password");
String directory = logsftpMap.get("isc.sso.log.sftp.directory");
ChannelSftp sftp = sf.connect(host, port, username, password);
sf.upload(directory, fileName, sftp);
// 删除临时文件
FileUtils.deleteFile(fileName);
}
}
}

/**
* 查询日志文件,默认为当天日志文件

* @return 日志文件列表
*/
private List<Log> allList() {
Log entity = new Log();
String strdate = DateUtils.getDate();
try {
entity.setBeginDate(DateUtils.parseDate(strdate + " 00:00:00",
"yyyy-MM-dd HH:mm:ss"));
entity.setEndDate(DateUtils.parseDate(strdate + " 23:59:59",
"yyyy-MM-dd HH:mm:ss"));
// return logDao.findListBySSO(entity);
return logDao.findList(entity);
} catch (ParseException e) {
LOG.info("查询日志数据库信息失败:" + e.getMessage());
return null;
}

}

/**
* 把日志记录转换4a需要的格式

* @param logList
* @return
*/
private List<String> logToString(List<Log> logList) {
List<String> result = new ArrayList<String>(logList.size());
for (Log log : logList) {
StringBuffer sb = new StringBuffer();
// appID
sb.append("appID=\"" + logsftpMap.get("ims.appid") + "\" ");
// appName
sb.append("appName=\"" + logsftpMap.get("ims.appName") + "\" ");
// logTime
sb.append("logTime=\""
+ DateUtils.formatDateTime(log.getCreateDate()) + "\" ");
// mainAccount
sb.append("mainAccount=\"" + log.getCreateBy().getLoginName()
+ "\" ");
// secondAccount
sb.append("secondAccount=\"" + log.getCreateBy().getLoginName()
+ "\" ");
// resId
sb.append("resId=\"" + log.getRequestUri() + "\" ");
// resName
sb.append("resName=\"" + log.getTitle() + "\" ");
// sIp
sb.append("sIp=\"" + log.getRemoteAddr() + "\" ");
// appModule
sb.append("appModule=\"" + "" + "\" ");
// opType
if (null != log.getTitle()) {
sb.append("opType=\"" + getOpType(log.getTitle().trim())
+ "\" ");
}
// opContent
sb.append("opContent=\"" + log.getParams() + "\" ");
// opResult
sb.append("opResult=\"" + "成功" + "\" ");
// logLevel
sb.append("logLevel=\"" + "一般" + "\" ");
result.add(sb.toString());
}
return result;

}

/**
* 根据日志记录中的标题设置日志文件的操作状态

* @param title
* @return
*/
private String getOpType(String title) {
// 默认为“查看操作”
String result = "View";
// 根据title 进行判断
if (title.indexOf("-查看") >= 0 || title.indexOf("-查看") >= 0) {
return "View";
}
if (title.indexOf("-修改") >= 0 || title.indexOf("-编辑") >= 0) {
return "Update";
}
if (title.indexOf("-新增") >= 0 || title.indexOf("-保存") >= 0) {
return "Add";
}
if (title.indexOf("系统登录") >= 0) {
return "Login";
}
return result;
}

/**
* 写日志文件

* @param path
* @param failures
*/
private static void writeFailures(String path, List<String> failures) {
try {
FileWriter fw = new FileWriter(path);
for (int i = 0; i < failures.size(); i++) {
String temp = failures.get(i);
fw.write(temp);
fw.write(System.getProperty("line.separator"));
}
fw.flush();
fw.close();
} catch (Exception e) {
e.printStackTrace();
LOG.info("写日志临时文件失败:" + e.getMessage());
}

}

/**
* 新建日志文件

* @param fileName
* @return
*/
private boolean createFile(String fileName) {
File file = new File(fileName);
if (file.exists()) {
return true;
}
if (fileName.endsWith(File.separator)) {
LOG.info(fileName + " 为目录,不能创建目录!");
return false;
}
if (!file.getParentFile().exists()) {
// 如果文件所在的目录不存在,则创建目录
if (!file.getParentFile().mkdirs()) {
LOG.info("创建文件所在的目录失败!");
return false;
}
}
// 创建文件
try {
if (file.createNewFile()) {
LOG.info(fileName + " 文件创建成功!");
return true;
} else {
LOG.info(fileName + " 文件创建失败!");
return false;
}
} catch (Exception e) {
e.printStackTrace();
LOG.info(fileName + " 文件创建失败!");
return false;
}

}

}

————————————————————————————————————————————————————

SFTPHandle.java

package com.nari.misp.webservice.modules.isc;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.util.Properties;

import java.util.Vector;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Channel;

import com.jcraft.jsch.ChannelSftp;

import com.jcraft.jsch.JSch;

import com.jcraft.jsch.Session;

import com.jcraft.jsch.SftpException;

public class SFTPHandle {
/**
* 日志对象
*/
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 连接sftp服务器

* @param host
*            主机
* @param port
*            端口
* @param username
*            用户名
* @param password
*            密码
* @return
*/
public ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
logger.info("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
logger.info("Session connected.");
logger.info("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
logger.info("Connected to " + host + ".");
} catch (Exception e) {

}
return sftp;
}

/**
* 上传文件

* @param directory
*            上传的目录
* @param uploadFile
*            要上传的文件
* @param sftp
*/
public void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 下载文件

* @param directory
*            下载目录
* @param downloadFile
*            下载的文件
* @param saveFile
*            存在本地的路径
* @param sftp
*/
public void download(String directory, String downloadFile,
String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 删除文件

* @param directory
*            要删除文件所在目录
* @param deleteFile
*            要删除的文件
* @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 列出目录下的文件

* @param directory
*            要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp)
throws SftpException {
return sftp.ls(directory);
}

public static void main(String[] args) {
SFTPHandle sf = new SFTPHandle();
String host = "10.50.30.75";
int port = 22;
String username = "logsftp";
String password = "logsftp";
String directory = "/home/logsftp/4a/logs/";
String uploadFile = "D:\\tmp\\20160318.syslog";

// String downloadFile = "upload.txt";

// String saveFile = "D:\\tmp\\download.txt";

// String deleteFile = "delete.txt";
ChannelSftp sftp = sf.connect(host, port, username, password);
sf.upload(directory, uploadFile, sftp);
//sf.download(directory, downloadFile, saveFile, sftp);

// sf.delete(directory, deleteFile, sftp);

// try {

// sftp.cd(directory);

// sftp.mkdir("ss");

// System.out.println("finished");

// } catch (Exception e) {

// e.printStackTrace();

// }
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: