TnPerl.java 6.54 KB
package com.sitech.util.upload;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import com.sitech.base.AgentProperties;
import com.sitech.util.Formater;
import com.sitech.util.JSONUtil;
import com.sitech.util.RandomGUID;
import com.sitech.util.SameGUID;
import com.sitech.util.SysHelper;

public class TnPerl {
	private Logger logger = Logger.getLogger(TnPerl.class);
	private static long TIME_OUT = 3 * 60 * 1000l;
	
	public List<String> doCommand(String ipAddr, String port, String user,
			String pwd, String cmd) throws Exception{
		List<String> cmdList = new ArrayList<String>();
		cmdList.add(cmd);
		
		List<List<String>> rst = doCommand(ipAddr, port, user, pwd, cmdList);
		if(null != rst && !rst.isEmpty()){
			return rst.get(0);
		}
		
		return null;
	}
	
	/**
	 * 通过perl远程telent登录,并执行多个命令
	 * @param ipAddr
	 * @param port
	 * @param user
	 * @param pwd
	 * @param cmdList
	 * @return
	 * @throws Exception
	 */
	public List<List<String>> doCommand(String ipAddr, String port, String user,
			String pwd, List<String> cmdList) throws Exception{
		TnPerlHandler handler = new TnPerlHandler();
		
		String guid = SameGUID.getSameGUID(ipAddr+"_"+user+"_"+JSONUtil.toJSON(cmdList));
		
		// 生成perl脚本
		String perlName = AgentProperties.AGENT_HOME + "/script/ibm/" + guid +".pl";
		String perlContent = handler.getContent(ipAddr, port, user, pwd, cmdList);
		handler.writeFile(perlName, perlContent);
		
		// 生成shell脚本
		String tmpName = AgentProperties.AGENT_HOME + "/result_temp/" + guid + ".rst";
		String rstName = AgentProperties.AGENT_HOME + "/result/" + guid + ".rst";
		String shellName = AgentProperties.AGENT_HOME + "/script/ibm/" + guid + ".sh";		
		//--------------------------------------------------------------------------------------------------
		// perl /bnms/agent/masteragent/script/ibm/guid.pl > /bnms/agent/masteragent/script/result_temp/guid.rst
		// mv /bnms/agent/masteragent/script/result_temp/guid.rst /bnms/agent/masteragent/script/result/guid.rst
		//--------------------------------------------------------------------------------------------------
		String shellContent = "perl " + perlName + " > " + tmpName + "\n";
		shellContent +=  "mv " + tmpName + " " + rstName;
		handler.writeFile(shellName, shellContent);
		
		// 生成notice文件
		String noticeName = AgentProperties.AGENT_HOME + "/notice/ibm/" + guid + ".sh";
		handler.writeFile(noticeName, noticeName);
		
		// 等待脚本执行完毕
		return getResult(rstName, cmdList);
	}

	/**
	 * 解析执行结果
	 * @param rstName
	 * @param cmdList
	 * @return
	 */
	private List<List<String>> getResult(String rstName,
			List<String> cmdList) {
		long beginTime = System.currentTimeMillis();
		
		List<List<String>> result = new ArrayList<List<String>>();

		while (true) {
			if (System.currentTimeMillis() - beginTime > TIME_OUT) {
				logger.warn("[Perl]TIME_OUT, exit :" + JSONUtil.toJSON(cmdList));
				break;
			}

			File rstFile = new File(rstName);
			if (null == rstFile || !rstFile.exists()) {
				SysHelper.waitIt(this, 2 * 1000L);
				continue;
			}
			
			int idx = 0;
			BufferedReader br = null;
			try {
				br = new BufferedReader(new FileReader(rstName));
				String line = "";
				while ((line = br.readLine()) != null) {
					List<String> list = result.get(idx);
					if(null == list.get(idx)){
						list = new ArrayList<String>();
						result.add(idx, list);
					}

					if (line.trim().equals("--- " + idx + " ---")) {
						idx++;
						continue;
					} else if (!line.trim().equals("")) {
						list.add(line);
					}
				}			
			} catch (Exception e) {
				logger.error("[Perl] Exception while readFile:" + rstName, e);
			}finally{
				if(br != null){
					try {
						br.close();
					} catch (IOException e) {
						logger.error("[Perl] IOException:", e);
					}
				}
				
			}
			
			break;
		}

		return result;
	}
	
	public static void main(String[] args) throws Exception {
		try{
			Map<String, String> params = new HashMap<String, String>();

			params.put("V_TELNET_PORT", "23");
			params.put("V_IP_ADDR", "172.21.0.31");
			params.put("V_USERNAME", "yfbnms");
			params.put("V_PASSWORD", "yfbnms");
			String context =  new TnPerlHandler().getContent(params, new ArrayList<String>());
			
			System.out.println(context);
		}catch(Exception e){
			e.printStackTrace();
		}

	}

}

class TnPerlHandler{

	/**
	 * 生成perl脚本
	 * @param ipAddr
	 * @param port
	 * @param user
	 * @param pwd
	 * @param cmdList
	 * @return
	 * @throws Exception
	 */
	public String getContent(String ipAddr, String port, String user,
			String pwd, List<String> cmdList) throws Exception {
		Map<String, String> params = new HashMap<String, String>();

		params.put("V_TELNET_PORT", port);
		params.put("V_IP_ADDR", ipAddr);
		params.put("V_USERNAME", user);
		params.put("V_PASSWORD", pwd);


		return getContent(params, cmdList);
	}

	/**
	 * 生成perl脚本
	 * @param params
	 * @param cmdList
	 * @return
	 * @throws Exception
	 */
	public String getContent(Map<String, String> params,
			List<String> cmdList) throws Exception {
		VelocityContext vc = new VelocityContext();
		for (String key : params.keySet()) {
			vc.put(key, params.get(key));
		}

		StringWriter writer = new StringWriter();
		
		VelocityEngine ve = new VelocityEngine();
		Properties p = new Properties();
		p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, AgentProperties.AGENT_HOME + "/config/velocity/");
		ve.init(p);
		
		ve.getTemplate("perl_telnet.vm").merge(vc, writer);

		String context = writer.toString() + "\n";

		for (int i = 0; i < cmdList.size(); i++) {
			String cmd = cmdList.get(i);
			context += "my @output" + i + " = $conn->cmd(\"" + cmd + "\");\n";
			context += "print @output" + i + ";\n";
			context += "print \"\n--- " + i + " ---\n\";\n";
		}


		return context;
	}
	

	
	public void writeFile(String shellName, String content) throws Exception{
		PrintWriter kpiFileStream = null;
		try {
			kpiFileStream = new PrintWriter(new FileWriter(Formater.replaceSpace(shellName), false), true);
			kpiFileStream.println(content);
		} catch (IOException e) {
			throw e;
		}finally{
			if(kpiFileStream != null){
				kpiFileStream.flush();
				kpiFileStream.close();
			}
		}		
	}
}