java路由器
① 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: ([^<]+)</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&®Ex.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){}}}