package com.epri.dchmi.ExecUtil; import java.util.ArrayList; import java.util.List; public class ExecResult { private boolean execFlag; private List<String> execList; public boolean isExecFlag() { return execFlag; } public ExecResult() { execList = new ArrayList<String>(); // TODO Auto-generated constructor stub } public void setExecFlag(boolean execFlag) { this.execFlag = execFlag; } public List<String> getExecList() { return execList; } public void setExecList(List<String> execList) { this.execList = execList; } }
package com.epri.dchmi.exportUtil; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Properties; /** * @Auther: feifei * @Date: 2019/8/12 13:46 * @Description:读取配置文件信息 */ public class PropertiesUtil { public static Properties getProperties(String fileName){ Properties pr = new Properties(); InputStream is = PropertiesUtil.class.getResourceAsStream("/"+fileName); try { pr.load(new InputStreamReader(is,"UTF-8")); is.close(); } catch (IOException e) { e.printStackTrace(); }finally{ if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return pr; } }
package com.epri.dchmi.ExecUtil; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.SCPClient; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RemoteExecuteCommand { public static Map<String,String> consoleMap = new HashMap<>(); private static String DEFAULTCHART = "GBK"; private Connection conn; private String hostName; private String userName; private String password; public RemoteExecuteCommand(String hostName, String userName, String password) { super(); this.hostName = hostName; this.userName = userName; this.password = password; } public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } /** * 检查是否登录 * @return */ public Boolean login(){ boolean flag = false; if(null==conn){ try{ System.out.println("连接到: "+this.hostName); conn = new Connection(hostName); conn.connect(); flag = conn.authenticateWithPassword(userName, password); }catch(Exception e){ e.printStackTrace(); } }else{ flag = true; } return flag; } //TODO public String execute(String cmd){ List<Map<String,Object>> retList = new ArrayList<Map<String,Object>>(); Session sess = null; String flag = "false"; try{ if(login()){ System.out.println("连接成功"); sess= conn.openSession(); System.out.println("开始执行程序"+cmd); sess.execCommand(cmd); String result=processStdout(sess.getStdout(),DEFAULTCHART); //如果为得到标准输出为空,说明脚本执行出错了 if(StringUtils.isBlank(result)){ result=processStdout(sess.getStderr(),DEFAULTCHART); System.out.println("============"); } // InputStream buffer = new StreamGobbler(); System.out.println("执行程序"+cmd+"结束"); flag = "true"; return flag; } }catch(Exception e){ e.printStackTrace(); }finally{ sess.close(); conn.close(); } return flag; } public byte[] downLoadFile(String remoteFile){ Session sess = null; try{ if(login()){ System.out.println("连接成功准备下载文件 "+remoteFile); SCPClient client = new SCPClient(conn); sess = conn.openSession(); byte[] bs = getRemoteFileBytes(client,remoteFile); System.out.println("下载数据大小为"+bs.length); return bs; } }catch(Exception e){ e.printStackTrace(); }finally{ sess.close(); conn.close(); } return null; } public Boolean uploadFile(byte[] bytes, String fileName,String tagetDirectory){ Session sess = null; try{ if(login()){ System.out.println("连接成功,准备上传文件 "+fileName); SCPClient client = new SCPClient(conn); sess = conn.openSession(); System.out.println("数据流大小"+bytes.length); System.out.println("存储路径"+tagetDirectory); client.put(bytes, fileName, tagetDirectory); System.out.println("上传成功"); return true; } }catch(Exception e){ e.printStackTrace(); }finally{ sess.close(); conn.close(); } return false; } private byte[] getRemoteFileBytes(SCPClient client,String remoteFile) throws IOException{ ByteArrayOutputStream stream = new ByteArrayOutputStream(); client.get(remoteFile, stream); stream.flush(); byte[] bytes = stream.toByteArray(); stream.close(); return bytes; } /** * 解析脚本执行返回的结果集 * @author Ickes * @param in 输入流对象 * @param charset 编码 * @since V0.1 * @return * 以纯文本的格式返回 */ private String processStdout(InputStream in, String charset){ InputStream stdout = new StreamGobbler(in); StringBuffer buffer = new StringBuffer();; try { BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset)); String line=null; while((line=br.readLine()) != null){ buffer.append(line+"\n"); //System.out.println(line+"========="); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer.toString(); } }
package com.epri.dchmi.ExecUtil; import com.jcraft.jsch.*; import com.jcraft.jsch.ChannelSftp.LsEntry; import java.io.*; import java.lang.reflect.Field; import java.net.URLEncoder; import java.util.Iterator; import java.util.Properties; import java.util.Vector; public class SftpManager { public static final String SFTP_PROTOCAL = "sftp"; private static String REMOTEPATH; private static String HOST; private static String USER; private static String PASSWORD; static { Properties SSH2_PROPERTIES = PropertiesUtil.getProperties("mapping.properties"); REMOTEPATH = SSH2_PROPERTIES.getProperty("REMOTEPATH"); HOST = SSH2_PROPERTIES.getProperty("HOST"); USER = SSH2_PROPERTIES.getProperty("USER"); PASSWORD = SSH2_PROPERTIES.getProperty("PASSWORD"); } /** * 创建SFTP连接 * * @param host * 主机IP * @param username * 主机登陆用户名 * @param password * 主机登陆密码 * @param port * 主机SSH登陆端口,如果port <= 0取默认值(22) * * @return SFTP * @throws Exception */ public static ChannelSftp connect(String host, String username, String password, int port) throws Exception { Channel channel = null; ChannelSftp sftp = null; JSch jsch = new JSch(); // 获取连接session Session session = createSession(jsch, host, username, port); // 设置登陆主机的密码 session.setPassword(password); // 设置登陆超时时间 session.connect(15000); System.out.println("Session connected to " + host + "."); try { // 创建SFTP通信通道 channel = (Channel) session.openChannel(SFTP_PROTOCAL); channel.connect(1000); System.out.println("Channel created to " + host + "."); sftp = (ChannelSftp) channel; } catch (JSchException e) { System.out.println("exception when channel create."); } return sftp; } /** * 将本地工作站文件上传到对应的pas主机上。 * * @param fileNameVector * 上传文件名称集合 */ public static ExecResult uploadFiles(InputStream is, String fileName, String directory) { ExecResult result = new ExecResult(); try { // 创建SFTP连接 ChannelSftp sftp = connect(HOST, USER, PASSWORD, 22); // 使用反射修改server_version的默认值,解决中文乱码问题 Class c = ChannelSftp.class; Field f = c.getDeclaredField("server_version"); f.setAccessible(true); System.out.println("f为" + f); System.out.println("sftp为" + sftp); f.set(sftp, 2); sftp.setFilenameEncoding("GBK"); System.out.println("开始上传文件" + fileName + "到" + directory); try { createDir(directory, sftp); } catch (Exception e) { System.out.println("创建目录失败"); } sftp.put(is, directory + fileName); result.setExecFlag(true); result.getExecList().add("文件上传成功!"); is.close(); sftp.disconnect(); } catch (Exception e) { result.setExecFlag(false); e.printStackTrace(); } return result; } /** * 创建一个文件目录 */ public static void createDir(String createpath, ChannelSftp sftp) { try { if (isDirExist(createpath,sftp)) { sftp.cd(createpath); return; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if (isDirExist(filePath.toString(),sftp)) { sftp.cd(filePath.toString()); } else { // 建立目录 sftp.mkdir(filePath.toString()); // 进入并设置为当前目录 sftp.cd(filePath.toString()); } } sftp.cd(createpath); } catch (SftpException e) { System.out.println("创建目录失败"); } } /** * 判断目录是否存在 */ public static boolean isDirExist(String directory, ChannelSftp sftp) { boolean isDirExistFlag = false; try { SftpATTRS sftpATTRS = sftp.lstat(directory); isDirExistFlag = true; return sftpATTRS.isDir(); } catch (Exception e) { if (e.getMessage().toLowerCase().equals("no such file")) { isDirExistFlag = false; } } return isDirExistFlag; } /** * 判断文件是否存在 */ public static boolean isFileExist(String path,String fileName){ try { // 创建SFTP连接 ChannelSftp sftp = connect(HOST, USER, PASSWORD, 22); Class c = ChannelSftp.class; Field f = c.getDeclaredField("server_version"); f.setAccessible(true); System.out.println("f为" + f); System.out.println("sftp为" + sftp); f.set(sftp, 2); sftp.setFilenameEncoding("GBK"); // 使用反射修改server_version的默认值,解决中文乱码问题 try { if (isDirExist(path,sftp)) { sftp.cd(path); Vector v = sftp.ls(fileName); if(v.size()>0){ Iterator it = v.iterator(); while(it.hasNext()){ LsEntry entry = (LsEntry)it.next(); String fileN = entry.getFilename(); System.out.println(fileN); } return true; } } } catch (SftpException e) { System.out.println(e); } sftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } return false; } /** * 创建SFTP服务器连接session * * @param jsch * 需要用到jsch-0.1.54.jar包 * @param host * IP地址 * @param username * 用户名 * @param port * 端口号 * * @return session * @throws Exception */ private static Session createSession(JSch jsch, String host, String username, int port) throws Exception { Session session = null; if (port <= 0) { // 连接服务器,采用默认端口 session = jsch.getSession(username, host); } else { // 采用指定的端口连接服务器 session = jsch.getSession(username, host, port); } // 如果服务器连接不上,则抛出异常 if (session == null) { throw new Exception(host + "session is null"); } // 设置第一次登陆的时候提示,可选值:(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no"); // session.setConfig("kex", "diffie-hellman-group1-sha1"); return session; } public static void main(String[] args) throws FileNotFoundException { FileInputStream is = new FileInputStream("G:/湖南_20190417777.cime"); File aa = new File("E:/ies/aaa/"); String aaa = "湖南全网_201904230108.cime"; try { String bbb = URLEncoder.encode(aaa, "UTF-8"); System.out.println(bbb); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } // if(!aa.isDirectory()){ // aa.mkdirs(); // } System.out.println(aa.exists()); // SftpManager.uploadFiles(is, "湖南_20190417777.cime", // "/home/d5000/tianjin/data/clouddata_hn/HN/origion_cime/"); } }
package com.epri.dchmi.dts.controller; import java.io.*; import java.lang.reflect.Field; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSON; import com.epri.dchmi.ExecUtil.RemoteExecuteCommand; import com.epri.dchmi.ExecUtil.SftpManager; import com.epri.dchmi.dts.entity.Scenario; import com.epri.dchmi.dts.service.ScenarioService; import com.epri.dchmi.exportUtil.DownLoadFile; import com.epri.dchmi.exportUtil.PropertiesUtil; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.SftpException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.epri.dchmi.memdb.common.SimpleValueType; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.epri.common.base.BaseController; import com.epri.dchmi.dts.model.Pinggujieguo; import com.epri.dchmi.memdbutil.service.ModelService; import com.epri.common.util.XmlUtil; import org.springframework.web.bind.annotation.ResponseBody; /** * * <p>Title: PingGuJieGuoController</p> * <p>Description: </p> * @author feifei * @date 2016年4月2日 */ @Controller public class PingGuJieGuoController extends BaseController { static final Properties SSH2_PROPERTIES = PropertiesUtil.getProperties("mapping.properties"); String user = SSH2_PROPERTIES.getProperty("user"); String password = SSH2_PROPERTIES.getProperty("password"); @Autowired ScenarioService scenarioService; String downliadPath = PropertiesUtil.getProperties("mapping.properties").getProperty("PINGGUPATH"); public ModelService getModelService(String group, String scence) { ModelService mc = new ModelService(group, group, scence); return mc; } public Map<String, String[]> tableColumns; public PingGuJieGuoController() { /*midified by lvyan 20190814 * dEvalRslt类型的数据中的descoresum改为descore_sum * */ tableColumns = new HashMap<String, String[]>(); String[] dEvalRslt = new String[] { "id", "name", "descore_sum", "descore_items" }; String[] dEvalRsltItem = new String[] { "id", "rulename", "objname", "descore_sum", "isalive", "begin_tm", "end_tm" }; String[] denergyloss = new String[] { "id", "name", "tm_peak" }; tableColumns.put("dEvalRslt", dEvalRslt); tableColumns.put("dEvalRsltItem", dEvalRsltItem); tableColumns.put("denergyloss", denergyloss); } @RequestMapping("getJieGuo") public void getJieGuo(HttpServletRequest request, HttpServletResponse response) { String group = request.getParameter("group"); String scence = request.getParameter("scence"); String divType = request.getParameter("divType"); XmlUtil xmlutil = new XmlUtil(null); xmlutil.addHead(); ModelService mc = getModelService(group, scence); if (mc == null) { return; } JSONArray list = null; String[] s = this.tableColumns.get(divType); list = mc.getAllRecordsByTableAndColumns(divType, this.tableColumns.get(divType)); xmlutil = this.xmlHelper(this.tableColumns.get(divType), list); String res = xmlutil.getXml(); try { response.setContentType("text/xml; charset=UTF-8"); response.getWriter().write(res); } catch (IOException e) { e.printStackTrace(); } } @RequestMapping("getJieGuos") public void getJieGuos(HttpServletRequest request, HttpServletResponse response) { String group = request.getParameter("group"); String scence = request.getParameter("scence"); String divType = request.getParameter("divType"); XmlUtil xmlutil = new XmlUtil(null); xmlutil.addHead(); ModelService mc = getModelService(group, scence); if (mc == null) { return; } JSONArray list = null; String[] s = this.tableColumns.get(divType); list = mc.getAllRecordsByTableAndColumns(divType, this.tableColumns.get(divType)); xmlutil = this.xmlHelper(this.tableColumns.get(divType), list); String res = xmlutil.getXml(); try { response.setContentType("text/xml; charset=UTF-8"); response.getWriter().write(res); } catch (IOException e) { e.printStackTrace(); } } @RequestMapping("getChuShi") public synchronized void getChuShi(HttpServletRequest request, HttpServletResponse response) { String group = request.getParameter("group"); String scence = request.getParameter("scence"); String divType = request.getParameter("divType"); int type = Integer.parseInt(request.getParameter("type")); ModelService mc = getModelService(group, scence); if (mc == null) { return; } String[] columns = new String[] { "id", "name", "f1", "f2", "f3", "f4" }; JSONArray list = mc.getModelByTableAndId(columns,"devalloginit","type",SimpleValueType.INT_TYPE,type); XmlUtil xmlutil = new XmlUtil(null); xmlutil.addHead(); if (list == null) { return; } for (int j=0;j<list.size();++j) { JSONObject json = list.getJSONObject(j); Pinggujieguo chushi = JSONObject.toJavaObject(json, Pinggujieguo.class); xmlutil.setRowId(chushi.getId() + ""); xmlutil.setXmlData(chushi.getName()); xmlutil.setXmlData(chushi.getF1()); xmlutil.setXmlData(chushi.getF2()); xmlutil.setXmlData(chushi.getF3()); xmlutil.setXmlData(chushi.getF4()); } String res = xmlutil.getXml(); try { response.setContentType("text/xml; charset=UTF-8"); response.getWriter().write(res); } catch (IOException e) { e.printStackTrace(); } } private XmlUtil xmlHelper(String[] columns, JSONArray list) { XmlUtil result = new XmlUtil(null); result.addHead(); for (int j=0;j<list.size();++j) { JSONObject json = list.getJSONObject(j); Pinggujieguo naming = JSONObject.toJavaObject(json, Pinggujieguo.class); result.setRowId(naming.getId() + ""); SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd hh:mm:ss"); for (int i = 0; i < columns.length; i++) { if (columns[i] == "name") { result.setXmlData(naming.getName()); } else if (columns[i] == "descore_sum") { result.setXmlData(naming.getDescore_sum()); }else if (columns[i] == "descoresum") { result.setXmlData(naming.getDescoresum()); } else if (columns[i] == "descore_items") { result.setXmlData(naming.getDescore_items()); } else if (columns[i] == "rulename") { result.setXmlData(naming.getRulename()); } else if (columns[i] == "objname") { result.setXmlData(naming.getObjname()); } else if (columns[i] == "isalive") { result.setXmlData(naming.getIsalive() == 1 ? "是" : "否"); } else if (columns[i] == "begin_tm") { result.setXmlData(sdf.format(naming.getBegin_tm() * 1000)); } else if (columns[i] == "end_tm") { result.setXmlData(sdf.format(new Date( naming.getEnd_tm() * 1000))); } else if (columns[i] == "tm_peak") { //System.out.println(naming.getTmPeak()); if(naming.getTmPeak()!=null){ result.setXmlData(sdf.format(new Date( naming.getTmPeak() * 1000))); }else{ result.setXmlData("非法时间"); //如果表里面时间错误,则显示当前时间 } } } } return result; } @RequestMapping("ifExistPingGuFile") @ResponseBody public String ifExistPingGuFile(String fName,String scence){ //String fn = URLDecoder.decode(fileName)+".txt"; String fn = fName+".doc"; System.out.println("fn=========:"+fn); Boolean retFlag = false; retFlag = this.isFileExist(downliadPath, fn,scence); File folder = new File(downliadPath); Map<String,Object> map = new HashMap<>(); map.put("flag", retFlag); return JSON.toJSONString(map); } /** * 判断文件是否存在 */ public boolean isFileExist(String path,String fileName,String scence){ Scenario scenario = scenarioService.findById(Integer.valueOf(scence)); String inter_ip = scenario.getInter_ip(); try { // 创建SFTP连接 ChannelSftp sftp = SftpManager.connect(inter_ip, user, password, 22); Class c = ChannelSftp.class; Field f = c.getDeclaredField("server_version"); f.setAccessible(true); f.set(sftp, 2); sftp.setFilenameEncoding("GBK"); // 使用反射修改server_version的默认值,解决中文乱码问题 try { if (SftpManager.isDirExist(path,sftp)) { sftp.cd(path); System.out.println("filenamelist"+sftp.ls(fileName)); Vector v = sftp.ls(fileName); if(v.size()>0){ Iterator it = v.iterator(); while(it.hasNext()){ ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry)it.next(); String fileN = entry.getFilename(); System.out.println("fileN=="+fileN); } return true; } } } catch (SftpException e) { System.out.println(e); } sftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } return false; } @RequestMapping("downloadPingGuFile") public void downloadPingGuFile(HttpServletRequest request,HttpServletResponse response){ String fName = request.getParameter("fName"); String fn = fName+".doc"; String scence = request.getParameter("scence"); Scenario scenario = scenarioService.findById(Integer.valueOf(scence)); String inter_ip = scenario.getInter_ip(); byte[] bytes = null; String fileName = downliadPath + fn; String user = SSH2_PROPERTIES.getProperty("user"); String password = SSH2_PROPERTIES.getProperty("password"); RemoteExecuteCommand remote = new RemoteExecuteCommand(inter_ip, user, password); //bytes = DownLoadFile.downLoadFile(fileName); bytes = remote.downLoadFile(fileName); try { response.setContentType("application/octet-stream;charset=utf-8"); String fileN = URLEncoder.encode(fn, "utf-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileN); OutputStream out = response.getOutputStream(); out.write(bytes); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { PingGuJieGuoController p = new PingGuJieGuoController(); //p.downloadPingGuFile(); } }