packagecom.bijian.test;importjava.util.ArrayList;importjava.util.Hashtable;importjava.util.List;importorg.apache.oro.text.regex.MalformedPatternException;importcom.jcraft.jsch.ChannelShell;importcom.jcraft.jsch.JSch;importcom.jcraft.jsch.Session;importcom.jcraft.jsch.UserInfo;importexpect4j.Closure;importexpect4j.Expect4j;importexpect4j.ExpectState;importexpect4j.matches.EofMatch;importexpect4j.matches.Match;importexpect4j.matches.RegExpMatch;importexpect4j.matches.TimeoutMatch;public classShell {privateSession session;privateChannelShell channel;private static Expect4j expect = null;private static final long defaultTimeOut = 1000;private StringBuffer buffer = newStringBuffer();public static final int COMMAND_EXECUTION_SUCCESS_OPCODE = -2;public static final String BACKSLASH_R = "\r";public static final String BACKSLASH_N = "\n";public static final String COLON_CHAR = ":";public static String ENTER_CHARACTER =BACKSLASH_R;public static final int SSH_PORT = 22;//正则匹配,用于处理服务器返回的结果
public static String[] linuxPromptRegEx = new String[] { "~]#", "~#", "#", ":~#", "/$", ">"};public static String[] errorMsg = new String[] { "could not acquire the config lock "};//ssh服务器的ip地址
privateString ip;//ssh服务器的登入端口
private intport;//ssh服务器的登入用户名
privateString user;//ssh服务器的登入密码
privateString password;public Shell(String ip, intport, String user, String password) {this.ip =ip;this.port =port;this.user =user;this.password =password;
expect=getExpect();
}/*** 关闭SSH远程连接*/
public voiddisconnect() {if (channel != null) {
channel.disconnect();
}if (session != null) {
session.disconnect();
}
}/*** 获取服务器返回的信息
*@return服务端的执行结果*/
publicString getResponse() {returnbuffer.toString();
}//获得Expect4j对象,该对用可以往SSH发送命令请求
privateExpect4j getExpect() {try{
System.out.println(String.format("Start logging to %s@%s:%s", user, ip, port));
JSch jsch= newJSch();
session=jsch.getSession(user, ip, port);
session.setPassword(password);
Hashtable config = new Hashtable();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
localUserInfo ui= newlocalUserInfo();
session.setUserInfo(ui);
session.connect();
channel= (ChannelShell) session.openChannel("shell");
Expect4j expect= newExpect4j(channel.getInputStream(), channel.getOutputStream());
channel.connect();
System.out.println(String.format("Logging to %s@%s:%s successfully!", user, ip, port));returnexpect;
}catch(Exception ex) {
System.err.println("Connect to " + ip + ":" + port + "failed,please check your username and password!");
ex.printStackTrace();
}return null;
}/*** 执行配置命令
*@paramcommands 要执行的命令,为字符数组
*@return执行是否成功*/
public booleanexecuteCommands(String[] commands) {//如果expect返回为0,说明登入没有成功
if (expect == null) {return false;
}
System.out.println("----------Running commands are listed as follows:----------");for(String command : commands) {
System.out.println(command);
}
System.out.println("----------End----------");
Closure closure= newClosure() {public void run(ExpectState expectState) throwsException {
buffer.append(expectState.getBuffer());//buffer is string//buffer for appending//output of executed//command
expectState.exp_continue();
}
};
List lstPattern = new ArrayList();
String[] regEx=linuxPromptRegEx;if (regEx != null && regEx.length > 0) {synchronized(regEx) {for (String regexElement : regEx) {//list of regx like, :>, />//etc. it is possible//command prompts of your//remote machine
try{
RegExpMatch mat= newRegExpMatch(regexElement, closure);
lstPattern.add(mat);
}catch(MalformedPatternException e) {return false;
}catch(Exception e) {return false;
}
}
lstPattern.add(new EofMatch(new Closure() { //should cause//entire page to be//collected
public voidrun(ExpectState state) {
}
}));
lstPattern.add(new TimeoutMatch(defaultTimeOut, newClosure() {public voidrun(ExpectState state) {
}
}));
}
}try{boolean isSuccess = true;for(String strCmd : commands) {
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;
}
}returnisSuccess;
}catch(Exception ex) {
ex.printStackTrace();return false;
}
}//检查执行是否成功
private boolean isSuccess(ListobjPattern, String strCommandPattern) {try{boolean isFailed =checkResult(expect.expect(objPattern));if (!isFailed) {
expect.send(strCommandPattern);
expect.send("\r");return true;
}return false;
}catch(MalformedPatternException ex) {return false;
}catch(Exception ex) {return false;
}
}//检查执行返回的状态
private boolean checkResult(intintRetVal) {if (intRetVal ==COMMAND_EXECUTION_SUCCESS_OPCODE) {return true;
}return false;
}//登入SSH时的控制信息//设置不提示输入密码、不显示登入信息等
public static class localUserInfo implementsUserInfo {
String passwd;publicString getPassword() {returnpasswd;
}public booleanpromptYesNo(String str) {return true;
}publicString getPassphrase() {return null;
}public booleanpromptPassphrase(String message) {return true;
}public booleanpromptPassword(String message) {return true;
}public voidshowMessage(String message) {
}
}public static voidmain(String[] args) {
String ip= "192.168.156.109";int port = 22;
String user= "root";
String password= "111111";
String cmd[]= { "pwd", "ifconfig"};
Shell ssh= newShell(ip, port, user, password);
ssh.executeCommands(cmd);
System.out.println(ssh.getResponse());
ssh.disconnect();
}
}