JSCH + Expect4J,在标准.expect和.send之前需要额外的登录步骤

时间:2012-05-01 15:12:19

标签: java sockets ssh jsch

我写了一个将通过SSH登录的程序。此服务器需要额外的一步,因为当您提示“目的地:”时,您需要提供区号和电话号码的三位数字。所以,我要做的是让我的终端等待Destination:提示,给它我的六位数,然后查看结果提示,看看它在执行我的期望代码之前去了哪里。在Destination:提示符后面有五种可能的终端类型,这意味着我需要在使用正则表达式给出我的六个电话号码后测试返回的流。

我遇到困难的是弄清楚获取Destination的最佳方法:提示,发送我的数字,获取生成的代码以执行我的正则表达式,如果然后语句,然后将其传递到几个类之一我将从那时开始使用expect4j执行。我应该在移动到期望之前使用exec shell,如果是这样,我如何从中获取输入以运行正则表达式?我应该发送expect.expect(“目的地:”);然后是expect.send(“123456”);然后获取运行正则表达式的输入,如果是,我如何从中获取输入? (我的示例代码使用缓冲区,它以某种方式从execute方法获取它的信息,我真的不明白它是如何完全工作的),或者,我的最后一个选项,我应该构建我的示例代码的两个实例,一个使得session和ssh channel,发送我的电话号码,获取输入,运行正则表达式,然后将它发送到另一个expect4j类,用新变量运行剩余的期望并发送?

IN SHORT:据我所知,这是我的三个选项:运行一个exec shell,运行一个expect.expect和expect.send,然后再进入更复杂的列表构建等,或者使用expect方法运行两个列表,一个接一个。不确定要走哪条路,以及如何让我的输入回来运行正则表达式。

我设法让它登录我的五个终端选项中的一个,检查并断开连接,最近我构建了登录代码,提供数字,并用正则表达式读取结果代码以指示哪个我的五种类型。我无法让他们一起工作。

我的代码是基于http://nikunjp.wordpress.com/2011/07/30/remote-ssh-using-jsch-with-expect4j/

中的示例构建的
    package switchoverlay;

    import com.jcraft.jsch.ChannelShell;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    import expect4j.Closure;
    import expect4j.Expect4j;
    import expect4j.ExpectState;
    import expect4j.matches.Match;
    import expect4j.matches.RegExpMatch;
    import java.util.ArrayList;
    import java.util.Hashtable;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import org.apache.oro.text.regex.MalformedPatternException;



    public class SSHLogin {

            static final String controlB = "\u0002";
            static final String controlC = "\u0003"; 
            static final String controlV = "\u0016";
            static final String cr = "\u0013";
            static final String lf = "\u0010";
            static final String sp = "\u0032";

            String npa = OverlayGUI.tn.substring(1, 4); //Get first three digits from tn
            String nxx = OverlayGUI.tn.substring(5, 8); //Get first three digits from tn
            String xxxx = OverlayGUI.tn.substring(9, 13); //Get last four digits from tn

            private static final int COMMAND_EXECUTION_SUCCESS_OPCODE = -2;
            private static String ENTER_CHARACTER = "\r";  //NOT GOOD FOR A GTD5!
            private static final int SSH_PORT = 22;
            private List<String> loginLstCmds = new ArrayList<String>();
            private static String[] switchPromptRegEx = new String[]
            {"\r\nDestination: ", //npanxx
            "via.{12}\r\n"}; //controlB

            private Expect4j expect = null;
            private StringBuilder loginBuffer = new StringBuilder();
            private String userName;
            private String password;
            private String host;

            /**
            *
            * @param host
            * @param userName
            * @param password
            */
            public SSHLogin(String host, String userName, String password) {
                    this.host = host;
                    this.userName = userName;
                    this.password = password;
            }
            /**
            *
            * @param LoginCmdsToExecute
            */
            public String execute(List<String> LoginCmdsToExecute) {
                    this.loginLstCmds = LoginCmdsToExecute;

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

                    List<Match> lstPattern =  new ArrayList<Match>();
                    for (String regexElement : switchPromptRegEx) {
                            try {
                                    Match mat = new RegExpMatch(regexElement, closure);
                                    lstPattern.add(mat);
                            } catch (MalformedPatternException e) {
                                    e.printStackTrace();
                            } catch(Exception e) {
                                    e.printStackTrace();
                            }
                    }

                    try {                
                            expect = SSH();
                            boolean isSuccess = true;                

                            for(String strCmd : loginLstCmds) {
                                    isSuccess = isSuccess(lstPattern,strCmd);
                                    if (!isSuccess) {
                                            isSuccess = isSuccess(lstPattern,strCmd);
                                    }
                            }

                            checkResult(expect.expect(lstPattern));
                    } catch (Exception ex) {
                            ex.printStackTrace();
                    } finally {
                            testType();
                    }
                    return loginBuffer.toString();
            }
            /**
            *
            * @param objPattern
            * @param strCommandPattern
            * @return
            */
            private boolean isSuccess(List<Match> objPattern,String strCommandPattern) {
                    try {
                            boolean isFailed = checkResult(expect.expect(objPattern));

                            if (!isFailed) {

                                    expect.send(strCommandPattern);
                                    Thread.sleep( 8000);
                                    //expect.send(ENTER_CHARACTER);  //NOT GOOD FOR A GTD5!
                                    return true;
                            }
                            return false;
                    } catch (MalformedPatternException ex) {
                            ex.printStackTrace();
                            return false;
                    } catch (Exception ex) {
                            ex.printStackTrace();
                            return false;
                    }
            }
            /**
            *
            * @param hostname
            * @param username
            * @param password
            * @param port
            * @return
            * @throws Exception
            */
            private Expect4j SSH() throws Exception {
                    JSch jsch = new JSch();
                    Session session = jsch.getSession(userName, host, SSH_PORT);
                    if (password != null) {
                            session.setPassword(password);
                    }
                    Hashtable<String,String> config = new Hashtable<String,String>();
                    config.put("StrictHostKeyChecking", "no");
                    session.setConfig(config);
                    session.connect(120000);
                    ChannelShell channel = (ChannelShell) session.openChannel("shell");
                    channel.connect();                   
                    Expect4j expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());          

                    return expect;              
            }
            /**
            *
            * @param intRetVal
            * @return
            */
            private boolean checkResult(int intRetVal) {
                    if (intRetVal == COMMAND_EXECUTION_SUCCESS_OPCODE) {
                            return true;
                    }
                    return false;
            }
            /**
            *
            */
            private void testType() {
            String lBString = loginBuffer.toString();
            System.out.println(lBString);


            Pattern gtd5 = Pattern.compile(".*GTD5.*");         
            Matcher gtd5Matcher = gtd5.matcher(lBString);
            if (gtd5Matcher.find()) {
                System.out.println("Your switch type is GTD5");
            }

            Pattern dms10 = Pattern.compile(".*DMS10^0.*");         
            Matcher dms10Matcher = dms10.matcher(lBString);
            if (dms10Matcher.find()) {
                System.out.println("Your switch type is DMS10");
            }

            Pattern dms100 = Pattern.compile(".*DMS100.*");         
            Matcher dms100Matcher = dms100.matcher(lBString);
            if (dms100Matcher.find()) {
                System.out.println("Your switch type is DMS100");
            }

            Pattern ess = Pattern.compile(".*5es.*");         
            Matcher essMatcher = ess.matcher(lBString);
            if (essMatcher.find()) {
                System.out.println("Your switch type is 5ESS");
            }

            Pattern dco = Pattern.compile(".*DCO.*");         
            Matcher dcoMatcher = dco.matcher(lBString);
            if (dcoMatcher.find()) {
                System.out.println("Your switch type is DCO");
            }


    //else { System.out.println("Switch type Error."); }

    //SSHGTD5ExamClient runSsh = new SSHGTD5ExamClient();  //pass on to expect4j based on regex for remaining expect and sends?

                                    //if (expect!=null) {  //old code for shutting down expect4j
                            //expect.close();



                    }


    }

0 个答案:

没有答案