CommandExecutor.java 8.76 KB
package com.sitech.ismp.check.mbean;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.HashMap;

import org.apache.log4j.Logger;

import com.sitech.ismp.check.util.RemoteController;
import com.sitech.ismp.check.util.RemoteControllerFactory;
import com.sitech.ismp.messageObject.cc.CommandParameters;
import com.sitech.ismp.messageObject.cc.CommandResults;
import com.sitech.util.RandomGUID;
import com.sitech.util.upload.FTPIF;
import com.sitech.util.upload.FTPSrv;
import com.sitech.util.upload.RomoteController;
import com.sitech.util.upload.SFTPClient;

public class CommandExecutor implements CommandExecutorMBean {

	public static String Exec_Flag_Success = "1";
	public static String Exec_Flag_Failure = "-1";
	public static String LOCAL_FILE_DIR = "../script/";
	private Logger logger = Logger.getLogger(CommandExecutor.class);
	
	boolean isConnect = false;

	public CommandResults executeCommands(CommandParameters cps) {
		HashMap _customProp = null;
		RomoteController rc = null;
		String _taskid = "";
		int _type = 0;
		String _content = "";
		
		String _hostip = "";
		String _hostusername = "";
		String _hostpassword = "";
		String _hostloginmode = "";
		
		Date _begintime = null;
		Date _endtime = null;
		String _execresult = "";
		String _execlog = "";
		String _execflag = Exec_Flag_Failure;
		String _failurereasion = "";
		
		_execlog = "指令执行器准备开始执行命令行\n";
		CommandResults crs = new CommandResults();
//		String res = init(cps);
		_customProp = cps.getCUSTOMPROP();
		_taskid = cps.getTASK_ID();
		_type = cps.getTYPE();
		// "cd /bnmsapp4/agent/bin;ksh startAll.sh"
//		_content = cps.getCONTENT();
		_content = "cd " + cps.getDB_URL() + ";sh " + cps.getCONTENT();
		logger.info("content is: " + _content);
		_hostip = cps.getHOST_IP();
		_hostusername = cps.getHOST_USERNAME();
		_hostpassword = cps.getHOST_PASSWORD();
		_hostloginmode = cps.getHOST_LOGIN_MODE();
		
		boolean fileFlag = false;
		boolean ftpFlag = false;
		String fileName = RandomGUID.getRandomGUID().substring(0,7) + ".sh";
		String localFilePath = LOCAL_FILE_DIR +File.separator+ fileName;
		// 生成采集脚本
		fileFlag = generateShell(localFilePath, _content);
		if(fileFlag){
			_execlog += "获取FTP连接\n";
			// 获取Ftp连接
			FTPIF ftpClient = getFtpClient(_hostip, _hostusername, _hostpassword);
			if (ftpClient == null) {
				_execlog += "FTP连接失败\n";
				logger.warn("ftpClient == null, return!");
			}else{
				_execlog += "FTP连接成功\n";
			}
			try{
				_execlog += "上传执行脚本\n";
				// 文件上传
				ftpClient.store(localFilePath, fileName);
				_execlog += "脚本上传成功\n";
				ftpFlag = true;
			}catch(Exception ex){
				logger.error("Ftp cccp shell to remote has err.",ex);
				_execlog += "脚本上传失败\n";
			}finally{
				try {
					ftpClient.logout();
				} catch (Exception e) {
					logger.error("Ftp disconnect failed!");
				}
			}
		}else{
			_execlog += "shell脚本生成失败!";
		}
		
		if(ftpFlag){
			_execlog += "准备连接SHELL命令主机"+_hostip+"\n";
			rc = RemoteControllerFactory.createRemoteController(_hostip, "SSH", _hostusername, _hostpassword);
			
			try {
				rc.initial();
				isConnect = true;
				_execlog += "ssh连接SHELL命令主机"+_hostip+"成功\n";
			} catch (Exception e) {
				isConnect = false;
				_execlog += "ssh连接SHELL命令主机"+_hostip+"失败\n";
				_failurereasion = e.getMessage();
				
				try{
					rc.close();
				}catch(Exception e1){
					
				}
				
				rc = RemoteControllerFactory.createRemoteController(_hostip, "TELNET", _hostusername, _hostpassword);
				
				try {
					rc.initial();
					isConnect = true;
					_execlog += "telnet连接SHELL命令主机"+_hostip+"成功\n";
				} catch (Exception e1) {
					isConnect = false;
					_execlog += "telnet连接SHELL命令主机"+_hostip+"失败\n";
					_failurereasion = e1.getMessage();
				}			
			}
			
			if (isConnect) {
				try {
					_begintime = new Date();
					rc.getResultAsStr("sh ./"+fileName);
					_execresult = rc.getResultAsStr("cat ./"+fileName);
					rc.getResultAsStr("rm ./"+fileName);
					_endtime = new Date();
					_execlog += "执行命令行结束\n";
					_execflag = Exec_Flag_Success;
				} catch (Exception e) {
					_endtime = new Date();
					e.printStackTrace();
					_execlog += "执行命令行结束\n";
					_execflag = Exec_Flag_Failure;
					_failurereasion = e.getMessage();
					_execresult = e.getMessage();
				} finally {
					crs.setTASK_ID(_taskid);
					crs.setTYPE(_type);
					crs.setBEGIN_TIME(_begintime);
					crs.setEND_TIME(_endtime);
					crs.setEXEC_RESULT(_execresult);
					crs.setEXEC_LOG(_execlog);
					crs.setEXEC_FLAG(_execflag);
					crs.setFAILURE_REASION(_failurereasion);
					crs.setCUSTOMPROP(_customProp);
				}
			} else {
				crs.setTASK_ID(_taskid);
				crs.setTYPE(_type);
				crs.setBEGIN_TIME(_begintime);
				crs.setEND_TIME(_endtime);
				crs.setEXEC_RESULT(_execresult);
				crs.setEXEC_LOG(_execlog);
				crs.setEXEC_FLAG(_execflag);
				crs.setFAILURE_REASION(_execlog);
				crs.setCUSTOMPROP(_customProp);
			}
			release(rc);
		}else{
			crs.setTASK_ID(_taskid);
			crs.setTYPE(_type);
			crs.setBEGIN_TIME(_begintime);
			crs.setEND_TIME(_endtime);
			crs.setEXEC_RESULT(_execresult);
			crs.setEXEC_LOG(_execlog);
			crs.setEXEC_FLAG(_execflag);
			crs.setFAILURE_REASION(_execlog);
			crs.setCUSTOMPROP(_customProp);
		}
		return crs;
	}
	
	public void release(RomoteController rc) {
		if (rc != null) {
			rc.close();
			rc = null;
		}
		System.gc();
	}

//	public String init(CommandParameters cps) {
//		_customProp = cps.getCUSTOMPROP();
//		_taskid = cps.getTASK_ID();
//		_type = cps.getTYPE();
//		// "cd /bnmsapp4/agent/bin;ksh startAll.sh"
////		_content = cps.getCONTENT();
//		_content = "cd " + cps.getDB_URL() + ";sh " + cps.getCONTENT();
//		System.out.println("content is: " + _content);
//		_hostip = cps.getHOST_IP();
//		_hostusername = cps.getHOST_USERNAME();
//		_hostpassword = cps.getHOST_PASSWORD();
//		_hostloginmode = cps.getHOST_LOGIN_MODE();
//		
//		if (String.valueOf(_type) != null && _type == 1) {
//			// SHELL指令方式
//			_execlog += "准备连接SHELL命令主机"+_hostip+"\n";
//			rc = RemoteControllerFactory.createRemoteController(_hostip, _hostloginmode, _hostusername, _hostpassword);
//		} else if (String.valueOf(_type) != null && (_type == 2 || _type == 3)) {
//			// SQL/存储过程指令方式,
//		}
//		try {
//			rc.initial();
//			isConnect = true;
//			_execlog += "连接SHELL命令主机"+_hostip+"成功\n";
//		} catch (Exception e) {
//			isConnect = false;
//			_execlog += "连接SHELL命令主机"+_hostip+"失败\n";
//			_failurereasion = e.getMessage();
//			return "连接主机" + _hostip + "失败";
//		}
//		return "SUCCESS";
//	}

	private FTPIF getFtpClient(String ip, String username, String password) {
		FTPIF ftpClient = new FTPSrv();
		try {
			logger.info("ftp " + ip + ", LOGIN:" + username + "...");

			ftpClient.login(ip, username, password);
		} catch (Exception e) {
			logger.warn("ftp " + ip + ", LOGIN:" + username + " FAILED!");
			try {
				ftpClient = new SFTPClient();
				logger.info("sftp " + username + "@" + ip);
				ftpClient.login(ip, username, password);
			} catch (Exception e1) {
				logger.warn("sftp " + username + "@" + ip + " FAILED!");
				ftpClient = null;
			}
		}
		return ftpClient;
	}
	/**
	 * 生成shell脚本
	 * @param filePath
	 * @param content
	 * @return
	 */
	private boolean generateShell(String filePath,String content){
		OutputStreamWriter writer = null;
		try{
			writer = new OutputStreamWriter(new FileOutputStream(new File(filePath)));
			String contents[] = content.split("\n");
			for(String c : contents){
				writer.write(c);
			}
			return true;
		}catch(Exception ex){
			logger.error("Cccp shell generate failed!",ex);
			return false;
		}finally{
			if(writer != null)
				try {
					writer.close();
				} catch (IOException e) {
					logger.error("Cccp shell output stream close err!",e);
					return false;
				}
			
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CommandExecutor ce = new CommandExecutor();
		CommandParameters cps = new CommandParameters();
//		cps.setCONTENT("stopAll.sh");cps.setDB_URL("/bnmsapp4/agent/bin")
		cps.setTASK_ID("TaskID-mooker");
		cps.setTYPE(1);
//		cps.setCONTENT("ls -l");
//		cps.setCONTENT("startAll.sh");
		cps.setCONTENT("stopAll.sh");
		cps.setDB_URL("/bnmsapp4/agent/bin");
		cps.setHOST_IP("172.21.0.117");
		cps.setHOST_USERNAME("bnmsapp4");
		cps.setHOST_PASSWORD("bnmsapp4");
		cps.setHOST_LOGIN_MODE("SSH");
		CommandResults cr = ce.executeCommands(cps);
		System.out.println(cr.getEXEC_LOG());
		System.out.println("执行结果:" + cr.getEXEC_RESULT());
	}

}