ShellExecutor.java 9.58 KB
package com.sitech.ismp.check.mbean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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 ShellExecutor implements ShellExecutorMBean {

	public static String Exec_Flag_Success = "1";
	public static String Exec_Flag_Failure = "-1";
	public static String LOCAL_FILE_DIR = "../script/";
	//public static String LOCAL_FILE_DIR = "E:\\workspace\\bomc4.0";
	private Logger logger = Logger.getLogger(CommandExecutor.class);
	
//	RemoteController rc = null;
//	private HashMap _customProp = 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 = "";
//	
//	boolean isConnect = false;
//	
	public CommandResults executeCommands(CommandParameters cps) {
		
		String _execlog = "指令执行器准备开始执行指令\n";
		CommandResults crs = new CommandResults();
//		String res = init(cps);
//		System.out.println("connect :"+res.trim().toUpperCase());
//		System.out.println("_taskid:"+_taskid);
		
		String _taskid = cps.getTASK_ID();
		int _type = cps.getTYPE();
		String _content = cps.getCONTENT();
		String _hostip = cps.getHOST_IP();
		String _hostusername = cps.getHOST_USERNAME();
		String _hostpassword = cps.getHOST_PASSWORD();
		String _hostloginmode = cps.getHOST_LOGIN_MODE();
		HashMap _customProp = cps.getCUSTOMPROP();

        if("127.0.0.1".equals(_hostip)){
            return new ShellExecutorThread().doCommandLocal(cps);
        }
		
		Date _begintime = null;
		Date _endtime = null;
		String _execresult = "";
		String _execflag = Exec_Flag_Failure;
		
		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){
			logger.info("获取FTP连接");
			_execlog += "获取FTP连接\n";
			// 获取Ftp连接
			FTPIF ftpClient = getFtpClient(_hostip, _hostusername, _hostpassword);
			if (ftpClient == null) {
				logger.info("FTP连接失败");
				_execlog += "FTP连接失败\n";
				logger.warn("ftpClient == null, return!");
			}else{
				logger.info("FTP连接成功");
				_execlog += "FTP连接成功\n";
			}
			try{
				logger.info("上传执行脚本");
				_execlog += "上传执行脚本\n";
				// 文件上传
				ftpClient.store(localFilePath, fileName);
				logger.info("脚本上传成功");
				_execlog += "脚本上传成功\n";
				ftpFlag = true;
			}catch(Exception ex){
				logger.error("Ftp cccp shell to remote has err.",ex);
				_execlog += "脚本上传失败\n";
			}finally{
				try {
					ftpClient.logout();
					// 删除本地生成的脚本文件
					File file = new File(localFilePath);
					file.deleteOnExit();
				} catch (Exception e) {
					logger.error("Ftp disconnect failed!");
				}
			}
		}else{
			_execlog += "shell脚本生成失败!";
		}
		
		if(ftpFlag){
			_execlog += "准备连接SHELL命令主机"+_hostip+"\n";
			RomoteController rc = RemoteControllerFactory.createRemoteController(_hostip, "SSH", _hostusername, _hostpassword);
			
			boolean isConnect = true;
			String _failurereasion = "";
			try {
				rc.initial();
				_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();
				}
				
			}
			System.out.println("cps.getTASK_ID()="+cps.getTASK_ID()+":isConnect="+isConnect);
			if (isConnect) {
				try {
					_begintime = new Date();
					String logName = fileName+".log";
					rc.getResultAsStr("sh ./"+fileName + " >> " + logName);
					_execresult = rc.getResultAsStr("cat ./"+logName);
					logger.info("***********************************\n"+_execresult+"\n***************************************");
					rc.getResultAsStr("rm ./"+fileName);
					rc.getResultAsStr("rm ./"+logName);
					System.out.println("cps.getTASK_ID()="+cps.getTASK_ID()+":_execresult="+_execresult);
					_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 String init(CommandParameters cps) {
//		_taskid = cps.getTASK_ID();
//		_type = cps.getTYPE();
//		_content = cps.getCONTENT();
//		_hostip = cps.getHOST_IP();
//		_hostusername = cps.getHOST_USERNAME();
//		_hostpassword = cps.getHOST_PASSWORD();
//		_hostloginmode = cps.getHOST_LOGIN_MODE();
//		_customProp = cps.getCUSTOMPROP();
//		
//		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/存储过程指令方式,此类处理的是SHELL指令方式
//		}
//		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";
//	}

	public void release(RomoteController rc) {
		if (rc != null) {
			rc.close();
			rc = null;
		}
		System.gc();
	}
	
	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");
			writer.write(content);
			//for(String c : contents){
				
			//}
			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;
				}
			
		}
	}
	
	public static void main(String[] args) {
		ShellExecutor se = new ShellExecutor();
		CommandParameters cps = new CommandParameters();
		cps.setTASK_ID("TaskID-mooker");
		cps.setTYPE(1);
//		cps.setCONTENT("cat /bnmsapp4/basd/webappserver/tomcat-5.5.27/conf/tomcat-users.xml");
		cps.setCONTENT("ping -c  3 127.0.0.1 | grep packets | awk '{print $7}'  | read count \n echo zhangdj=${count} \n echo mayi=10 \n echo linxc=0809");
		cps.setHOST_IP("172.21.1.69");
		cps.setHOST_USERNAME("yfbnms");
		cps.setHOST_PASSWORD("yfbnms");
		cps.setHOST_LOGIN_MODE("TELNET");
		CommandResults cr = se.executeCommands(cps);
		System.out.println(cr.getEXEC_RESULT());
	}
}