java连接ssh登陆路由器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java连接ssh登陆路由器相关的知识,希望对你有一定的参考价值。

连到路由器之后需要二次登陆,用什么可以获取到提示你登陆之后再输入用户名密码登陆

package com.flyingzl.ssh;import java.util.ArrayList
import java.util.Hashtable
import java.util.List
import org.apache.log4j.Logger
import org.apache.oro.text.regex.MalformedPatternException
import com.jcraft.jsch.ChannelShell
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import com.jcraft.jsch.UserInfo
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 Shell     private static Logger log = Logger.getLogger(Shell.class)
        private Session session
    private ChannelShell channel
    private static Expect4j expect = null
    private static final long defaultTimeOut = 1000
    private StringBuffer buffer=new StringBuffer()
        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地址    private String ip
    //ssh服务器的登入端口    private int port
    //ssh服务器的登入用户名    private String user
    //ssh服务器的登入密码    private String password
        public Shell(String ip,int port,String user,String password)         this.ip=ip
        this.port=port
        this.user=user
        this.password=password
        expect = getExpect()
            /**     * 关闭SSH远程连接     */    public void disconnect()        if(channel!=null)            channel.disconnect()
                if(session!=null)            session.disconnect()
                    /**     * 获取服务器返回的信息     * @return 服务端的执行结果     */    public String getResponse()        return buffer.toString()
            //获得Expect4j对象,该对用可以往SSH发送命令请求    private Expect4j getExpect()         try             log.debug(String.format("Start logging to %s@%s:%s",user,ip,port))
            JSch jsch = new JSch()
            session = jsch.getSession(user, ip, port)
            session.setPassword(password)
            Hashtable<String, String> config = new Hashtable<String, String>()
            config.put("StrictHostKeyChecking", "no")
            session.setConfig(config)
            localUserInfo ui = new localUserInfo()
            session.setUserInfo(ui)
            session.connect()
            channel = (ChannelShell) session.openChannel("shell")
            Expect4j expect = new Expect4j(channel.getInputStream(), channel                    .getOutputStream())
            channel.connect()
            log.debug(String.format("Logging to %s@%s:%s successfully!",user,ip,port))
            return expect
         catch (Exception ex)             log.error("Connect to "+ip+":"+port+"failed,please check your username and password!")
            ex.printStackTrace()
                return null
        /**     * 执行配置命令     * @param commands 要执行的命令,为字符数组     * @return 执行是否成功     */    public boolean executeCommands(String[] commands)         //如果expect返回为0,说明登入没有成功        if(expect==null)            return false
                        log.debug("----------Running commands are listed as follows:----------")
        for(String command:commands)            log.debug(command)
                log.debug("----------End----------")
                Closure closure = new Closure()             public void run(ExpectState expectState) throws Exception                 buffer.append(expectState.getBuffer())
// buffer is string                                                        // buffer for appending                                                        // output of executed                                                        // command                expectState.exp_continue()
                                    
        List<Match> lstPattern = new ArrayList<Match>()
        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 = new RegExpMatch(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 void run(ExpectState state)                                                     ))
                lstPattern.add(new TimeoutMatch(defaultTimeOut, new Closure()                     public void run(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
                                                    return isSuccess
         catch (Exception ex)             ex.printStackTrace()
            return false
                //检查执行是否成功    private boolean isSuccess(List<Match> objPattern, 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(int intRetVal)         if (intRetVal == COMMAND_EXECUTION_SUCCESS_OPCODE)             return true
                return false
            //登入SSH时的控制信息    //设置不提示输入密码、不显示登入信息等    public static class localUserInfo implements UserInfo         String passwd
        public String getPassword()             return passwd
                public boolean promptYesNo(String str)             return true
                public String getPassphrase()             return null
                public boolean promptPassphrase(String message)             return true
                public boolean promptPassword(String message)             return true
                public void showMessage(String message)                         
参考技术A 用apache的httpclient的api试试 参考技术B 推荐这篇文章:http://www.tuicool.com/articles/UBJrYn追问

我这个和连接linux不要一样,输入ip和端口之后要二次登陆,二次登陆的那个plese login:怎么获取

追答

那么就要用HttpClient来模拟登录了。
1、先把登录页面用谷歌浏览器打开;
2、按F12打开调试窗口
3、输入用户名、密码登录
4、查看调试窗口中的network页的request和response内容。
5、用HttpClient模拟登录。

路由交换学习第四天:路由器配置SSH认证登陆

华为路由器1:
<Huawei>sys //进入系统视图
[Huawei]interface g0/0/0 //进入g0/0/0配置
[Huawei-GigabitEthernet0/0/0]ip address 202.100.1.1 30 //配置IP地址为202.100.1.1 30
[Huawei-GigabitEthernet0/0/0]q
[Huawei]aaa //进入aaa
[HW-R1-aaa]local-user huawei password cipher huawei123 //创建用户huawei和密码huawei123
[Huawei-aaa]local-user huawei service-type ssh //用户huawei认证默认是SSH
[Huawei-aaa]local-user huawei privilege level 15 //用户huawei用户权限15级
[Huawei-aaa]q //退出
[Huawei]ssh user huawei authentication-type password //SSH用户huawei认证模式是密码认证
Authentication type setted, and will be in effect next time
[Huawei]stelnet server enable //开启SSH认证服务
Info: Succeeded in starting the STELNET server.
[Huawei]rsa local-key-pair create //生成本地认证秘钥
The key name will be: Host
% RSA keys defined for Host already exist.
Confirm to replace them? (y/n)[n]:y //是否确定更换现有秘钥(是)
The range of public key size is (512 ~ 2048).
NOTES: If the key modulus is greater than 512,
It will take a few minutes.
Input the bits in the modulus[default = 512]:768 //默认512位密码,输入产生的秘钥长度(768)
Generating keys...
................++++++++
.++++++++
.+++++++++
.+++++++++
[Huawei]user-interface vty 0 4 //进入配置虚拟终端
[Huawei-ui-vty0-4]authentication-mode aaa //虚拟终端认证模式为AAA
[Huawei-ui-vty0-4]protocol inbound ssh //开启SSH
[Huawei-ui-vty0-4]q //退出
[Huawei]sys HW-R1 //设置设备名称HW-R1
[HW-R1]

华为路由器2:

<Huawei>sys //进入系统视图
[Huawei]interface g0/0/0 //进入g0/0/0配置
[Huawei-GigabitEthernet0/0/0]ip address 202.100.1.2 30 //配置IP地址为202.100.1.2 30
[Huawei-GigabitEthernet0/0/0]q //退出
[Huawei]ssh client first-time enable //开启SSH第一次登陆
[Huawei]stelnet 202.100.1.1
Please input the username:huawei //输入用户名huawei
Trying 202.100.1.1 ...
Press CTRL+K to abort
Error: Failed to connect to the remote host.
[Huawei]stelnet 202.100.1.1
Please input the username:huawei
Trying 202.100.1.1 ...
Press CTRL+K to abort
Error: Failed to connect to the remote host.
[Huawei]stelnet 202.100.1.1
Please input the username:huawei
Trying 202.100.1.1 ...
Press CTRL+K to abort
Connected to 202.100.1.1 ...
The server is not authenticated. Continue to access it? (y/n)[n]:y //是否接收秘钥
Jul 29 2019 16:43:31-08:00 Huawei %%01SSH/4/CONTINUE_KEYEXCHANGE(l)[1]:The server had not been authenticated in the process of exchanging keys. When deciding whether to continue, the user chose Y.
[Huawei]
Save the server‘s public key? (y/n)[n]:y //是否保存秘钥在本地
The server‘s public key will be saved with the name 202.100.1.1. Please wait...

Jul 29 2019 16:43:33-08:00 Huawei %%01SSH/4/SAVE_PUBLICKEY(l)[2]:When deciding whether to save the server‘s public key 202.100.1.1, the user chose Y.
[Huawei]
Enter password: //输入密码
<Huawei>sys //进入系统视图
[HW-R1]
<HW-R1>dis users
User-Intf Delay Type Network Address AuthenStatus AuthorcmdFlag
0 CON 0 00:02:26 pass Username : Unspecified

  • 129 VTY 0 00:00:00 SSH 202.100.1.2 pass Username : huawei

以上是关于java连接ssh登陆路由器的主要内容,如果未能解决你的问题,请参考以下文章

为啥ssh可以连接telnet连不上

在LINUX系统下,如何使用SHell脚本,SSH登陆上路由器

路由交换学习第四天:路由器配置SSH认证登陆

路由器远程登陆的方式

什么命令将阻止使用Telnet,只允许使用SSH远程登陆路由器。

怎么用SSH登陆OpenWrt,服务端和客户端的设置方法