Linux上使用java代码实现Local Interactive Commands(such as:hprest;hpssacli)

实现Local Interactive Commands(本地的交互式命令)可以使用脚本方式:

也可以使用java代码在linux上实现:(此方法要在linux系统上运行,windows系统是不可以的)

http://blog.csdn.net/itzhangdaopin/article/details/53905385 有java打jar包在Linux上运行的例子,可供参考。

package com;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.oro.text.regex.MalformedPatternException;

import expect4j.Closure;
import expect4j.Expect4j;
import expect4j.ExpectState;
import expect4j.matches.EofMatch;
import expect4j.matches.Match;
import expect4j.matches.RegExpMatch;
import expect4j.matches.TimeoutMatch;

public class TestLocal {
	
	private static Logger log = Logger.getLogger(TestLocal.class);

	private static Expect4j expect = null;
	private static final long defaultTimeOut = 2000;
	private static StringBuffer buffer = new StringBuffer();
	
	public static String[] linuxPromptRegEx = new String[] { "~]#", "~#", "#", ":~#", "/$", ">" };
	public static String[] errorMsg = new String[] { "could not acquire the config lock " };
	
	public static void main(String[] args) throws Exception {
		String[] cmdArgs1={"hprest","help","logout"};
		expect = spawn(cmdArgs1);
		executeCommands(cmdArgs1);
		System.out.println(getResponse());
		disconnect();
	}
	
	protected static Expect4j spawn(String[] cmdArgs) throws Exception {
		ProcessBuilder pd;
        Process process = Runtime.getRuntime().exec(cmdArgs[0]);//取出第一个元素来进行运行(hprest;hpssacli)
        pd=new ProcessBuilder(cmdArgs[0]);
        pd.redirectErrorStream(true);
        process = pd.start();
        InputStream is = process.getInputStream();
        OutputStream os = process.getOutputStream();
        Expect4j expect = new Expect4j(is,os);
        
        return expect;
    }
	protected static void disconnect() {
	    	if (expect != null) {
	    		expect.close();
	    	}
		}
	
	
	public static boolean executeCommands(String[] commands) {
		
		if (expect == null) {
			return false;
		}

		log.debug("----------Running commands are listed as follows:----------");
		for (String command : commands) {
			log.debug(command);
			System.out.println(command);
		}
		log.debug("----------End----------");

		Closure closure = new Closure() {
			public void run(ExpectState expectState) throws Exception {
				buffer.append(expectState.getBuffer());
				expectState.exp_continue();

			}
		};
		List<Match> lstPattern = new ArrayList<Match>();
		String[] regEx = linuxPromptRegEx;
		if (regEx != null && regEx.length > 0) {
			synchronized (regEx) {
				// list of regx like, :>, /> etc. it is possible command prompts of your remote machine
				for (String regexElement : regEx) {
					try {
						RegExpMatch mat = new RegExpMatch(regexElement, closure);
						lstPattern.add(mat);
					} catch (MalformedPatternException e) {
						return false;
					} catch (Exception e) {
						return false;
					}
				}
				lstPattern.add(new EofMatch(new Closure() {
					public void run(ExpectState state) {
					}
				}));
				lstPattern.add(new TimeoutMatch(defaultTimeOut, new Closure() {
					public void run(ExpectState state) {
					}
				}));
			}
		}
		for (String regexElement : regEx) {
		RegExpMatch mat;
		try {
			mat = new RegExpMatch(regexElement, closure);
			lstPattern.add(mat);
		} catch (MalformedPatternException e) {
			e.printStackTrace();
		}
		}
		try {
			boolean isSuccess = true;
			//for (String strCmd : commands) {
			for (int i = 1; i < commands.length; i++) {//从第二个元素开始遍历,在第一个元素的条件下(如:hprest> xxx)运行命令
				String strCmd=commands[i];
				isSuccess = isSuccess(lstPattern, strCmd);
			}
			
			isSuccess = !checkResult(expect.expect(lstPattern));
			
			String response = buffer.toString().toLowerCase();
			for (String msg : errorMsg) {
				if (response.indexOf(msg) > -1) {
					return false;
				}
			}

			return isSuccess;
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}
	private static boolean isSuccess(List<Match> objPattern, String strCommandPattern) {
		try {
			boolean isFailed = checkResult(expect.expect(objPattern));
			if (!isFailed) {
				expect.send(strCommandPattern);
				expect.send("\n");
				expect.send("\r");
				return true;
			}
			return false;
		} catch (MalformedPatternException ex) {
			return false;
		} catch (Exception ex) {
			return false;
		}
	}

	private static boolean checkResult(int intRetVal) {
		if (intRetVal == -2) {
			return true;
		}
		return false;
	}

	public static String getResponse() {
		return buffer.toString();
	}
	
	
	
	
}


posted @ 2022-01-27 18:37  zhangdaopin  阅读(42)  评论(0编辑  收藏  举报