当前位置:首页 » 编程语言 » java路由器

java路由器

发布时间: 2023-02-24 14:01:20

java如何获取公网ip,有通过路由

如果要通过路由器,不同的路由器的获取方法不一样。通用的做法是通过 HttpClient 在网络上搜索关键字 ip, 然后提取出公网ip。

importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.net.URL;
importjava.net.URLConnection;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;

publicclassApp{

//获取网页源码
staticStringhttpGet(Stringurl){

StringBufferbuffer=newStringBuffer();

try{

URLConnectionconn=newURL(url).openConnection();

conn.addRequestProperty("User-Agent","Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/67.0.3396.99Safari/537.36");

try(InputStreaminputStream=conn.getInputStream();
InputStreamReaderstreamReader=newInputStreamReader(inputStream);
BufferedReaderreader=newBufferedReader(streamReader);){

Stringline=null;

while((line=reader.readLine())!=null){
buffer.append(line).append(System.lineSeparator());
}
}

}catch(IOExceptione){
e.printStackTrace();
}

returnbuffer.toString();
}

publicstaticvoidmain(String[]args){

Stringhtml=httpGet("https://www..com/s?wd=ip");

//提出IP

Patternpattern=Pattern.compile("<span\sclass="c-gap-right">本机IP:&nbsp;([^<]+)</span>");

Matchermatcher=pattern.matcher(html);

if(matcher.find()){

Stringip=matcher.group(1);

System.out.println(ip);
}

}
}

② java连接ssh登陆路由器

packagecom.flyingzl.ssh;importjava.util.ArrayList
importjava.util.Hashtable
importjava.util.List
importorg.apache.log4j.Logger
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
publicclassShell{privatestaticLoggerlog=Logger.getLogger(Shell.class)
privateSessionsession
privateChannelShellchannel
privatestaticExpect4jexpect=null
=1000
privateStringBufferbuffer=newStringBuffer()
publicstaticfinalintCOMMAND_EXECUTION_SUCCESS_OPCODE=-2
_R=" "
_N=" "
publicstaticfinalStringCOLON_CHAR=":"
publicstaticStringENTER_CHARACTER=BACKSLASH_R
publicstaticfinalintSSH_PORT=22
//正则匹配,用于处理服务器返回的结果publicstaticString[]linuxPromptRegEx=newString[]{"~]#","~#","#",":~#","/$",">"}
publicstaticString[]errorMsg=newString[]{"couldnotacquiretheconfiglock"}
//ssh服务器的ip地址privateStringip
//ssh服务器的登入端口privateintport
//ssh服务器的登入用户名privateStringuser
//ssh服务器的登入密码privateStringpassword
publicShell(Stringip,intport,Stringuser,Stringpassword){this.ip=ip
this.port=port
this.user=user
this.password=password
expect=getExpect()
}/***关闭SSH远程连接*/publicvoiddisconnect(){if(channel!=null){channel.disconnect()
}if(session!=null){session.disconnect()
}}/***获取服务器返回的信息*@return服务端的执行结果*/publicStringgetResponse(){returnbuffer.toString()
}//获得Expect4j对象,该对用可以往SSH发送命令请求privateExpect4jgetExpect(){try{log.debug(String.format("Startloggingto%s@%s:%s",user,ip,port))
JSchjsch=newJSch()
session=jsch.getSession(user,ip,port)
session.setPassword(password)
Hashtable<String,String>config=newHashtable<String,String>()
config.put("StrictHostKeyChecking","no")
session.setConfig(config)
localUserInfoui=newlocalUserInfo()
session.setUserInfo(ui)
session.connect()
channel=(ChannelShell)session.openChannel("shell")
Expect4jexpect=newExpect4j(channel.getInputStream(),channel.getOutputStream())
channel.connect()
log.debug(String.format("Loggingto%s@%s:%ssuccessfully!",user,ip,port))
returnexpect
}catch(Exceptionex){log.error("Connectto"+ip+":"+port+"failed,!")
ex.printStackTrace()
}returnnull
}/***执行配置命令*@paramcommands要执行的命令,为字符数组*@return执行是否成功*/publicbooleanexecuteCommands(String[]commands){//如果expect返回为0,说明登入没有成功if(expect==null){returnfalse
}log.debug("----------:----------")
for(Stringcommand:commands){log.debug(command)
}log.debug("----------End----------")
Closureclosure=newClosure(){publicvoidrun(ExpectStateexpectState)throwsException{buffer.append(expectState.getBuffer())
//bufferisstring//bufferforappending//outputofexecuted//commandexpectState.exp_continue()
}}
List<Match>lstPattern=newArrayList<Match>()
String[]regEx=linuxPromptRegEx
if(regEx!=null&&regEx.length>0){synchronized(regEx){for(StringregexElement:regEx){//listofregxlike,:>,/>//etc.itispossible//commandpromptsofyour//remotemachinetry{RegExpMatchmat=newRegExpMatch(regexElement,closure)
lstPattern.add(mat)
}catch(MalformedPatternExceptione){returnfalse
}catch(Exceptione){returnfalse
}}lstPattern.add(newEofMatch(newClosure(){//shouldcause//entirepagetobe//collectedpublicvoidrun(ExpectStatestate){}}))
lstPattern.add(newTimeoutMatch(defaultTimeOut,newClosure(){publicvoidrun(ExpectStatestate){}}))
}}try{booleanisSuccess=true
for(StringstrCmd:commands){isSuccess=isSuccess(lstPattern,strCmd)
}//防止最后一个命令执行不了isSuccess=!checkResult(expect.expect(lstPattern))
//找不到错误信息标示成功Stringresponse=buffer.toString().toLowerCase()
for(Stringmsg:errorMsg){if(response.indexOf(msg)>-1){returnfalse
}}returnisSuccess
}catch(Exceptionex){ex.printStackTrace()
returnfalse
}}//检查执行是否成功privatebooleanisSuccess(List<Match>objPattern,StringstrCommandPattern){try{booleanisFailed=checkResult(expect.expect(objPattern))
if(!isFailed){expect.send(strCommandPattern)
expect.send(" ")
returntrue
}returnfalse
}catch(MalformedPatternExceptionex){returnfalse
}catch(Exceptionex){returnfalse
}}//检查执行返回的状态privatebooleancheckResult(intintRetVal){if(intRetVal==COMMAND_EXECUTION_SUCCESS_OPCODE){returntrue
}returnfalse
}//登入SSH时的控制信息//设置不提示输入密码、不显示登入信息等{Stringpasswd
publicStringgetPassword(){returnpasswd
}publicbooleanpromptYesNo(Stringstr){returntrue
}publicStringgetPassphrase(){returnnull
}publicbooleanpromptPassphrase(Stringmessage){returntrue
}publicbooleanpromptPassword(Stringmessage){returntrue
}publicvoidshowMessage(Stringmessage){}}}

热点内容
网易云音乐文件夹名 发布:2024-11-07 22:39:23 浏览:210
云速服务器近期价格 发布:2024-11-07 22:39:20 浏览:37
linuxnginx与php 发布:2024-11-07 22:33:32 浏览:78
android语音sdk 发布:2024-11-07 22:26:58 浏览:614
uuidjava生成 发布:2024-11-07 22:22:31 浏览:7
装修家中需要配置哪些东西 发布:2024-11-07 22:21:11 浏览:82
什么安卓的平板电脑最好用 发布:2024-11-07 22:21:05 浏览:553
linux最大内存 发布:2024-11-07 22:11:28 浏览:627
谁编程的楚辞 发布:2024-11-07 22:06:22 浏览:334
安卓暴力摩托叫什么 发布:2024-11-07 22:05:03 浏览:344