A. 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){}}}
B. 怎么用java实现ssh协议通信
importch.ethz.ssh2.Connection;
importch.ethz.ssh2.Session;
importch.ethz.ssh2.StreamGobbler;
importcom.io.Debug;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
/**
*
*@authorleon.lee
*/
{
privateStringusername="";
privateStringoldpassword="";
privateConnectionconn=;
privatebooleanhasError=false;
privateStringErrorMessage="";
privatebooleanisSuccessfully=false;
privateStringSystemMessage="";
publicstaticfinalStringHOST="127.0.0.1";//serverip
publicbooleanisSuccessfully(){
returnisSuccessfully;
}
publicbooleanisHasError(){
returnhasError;
}
publicStringgetErrorMessage(){
returnErrorMessage;
}
publicvoidsetErrorMessage(Stringmsg){
hasError=true;
this.ErrorMessage=msg;
}
/**
*Createsanewinstanceof<code>ChangeEmailPassword</code>.
*@paramusername
*@paramoldpassword
*/
publicChangeEmailPassword(Stringusername,Stringoldpassword){
this.username=username;
this.oldpassword=oldpassword;
try{
conn=newConnection(HOST);
conn.connect();
/*Authenticate*/
booleanisAuthenticated=conn.authenticateWithPassword(username,oldpassword);
if(isAuthenticated==false){
setErrorMessage("Authenticationfailed.");
conn=;
}
}catch(Exceptione){
conn.close();
conn=;
System.out.println(e);
}
}
publicvoidsetNewPassword(Stringnewpassword){
if(hasError){
return;
}
if(conn==){
return;
}
try{
Sessionsess=conn.openSession();
sess.execCommand("passwd");
InputStreamso=sess.getStdout();
InputStreamerr=sess.getStderr();
OutputStreamout=sess.getStdin();
byte[]buffer=newbyte[500];//其实没有必要这么大.130就差不多了.怕万一有什么提示.
intlength=0;
length=err.read(buffer);
//if(length>0){
//System.out.println("#1:"+newString(buffer,0,length));
////(current)UNIXpassword:
//}
Stringcoldpassword=oldpassword+" ";
out.write(coldpassword.getBytes());
length=err.read(buffer);
//if(length>0){
//System.out.println("#2:"+newString(buffer,0,length));
////(current)UNIXpassword:
//}
Stringcnewpass=newpassword+" ";
out.write(cnewpass.getBytes());
length=err.read(buffer);
if(length>0){
Stringrs=newString(buffer,0,length);
//System.out.println("#3:"+rs);
if(rs.indexOf("BAD")>-1){
sess.close();
conn.close();
setErrorMessage(rs);
return;
}
}
out.write(cnewpass.getBytes());
length=so.read(buffer);
if(length>0){
Stringrs=newString(buffer,0,length);
if(rs.indexOf("successfully")>-1){
this.isSuccessfully=true;
this.SystemMessage=rs;
}
}
/*Closethissession*/
sess.close();
/*Closetheconnection*/
conn.close();
}catch(IOExceptione){
e.printStackTrace(System.err);
}
}
/**
*@
*/
publicstaticvoidmain(String[]args){
ChangeEmailPasswordcep=newChangeEmailPassword("username","oldpassword");
if(cep.isHasError()){
System.out.println(cep.getErrorMessage());
cep=;
return;
}
cep.setNewPassword("newpassword");
if(cep.isHasError()){
System.out.println(cep.getErrorMessage());
cep=;
return;
}
if(cep.isSuccessfully){
System.out.println(cep.getSystemMessage());
}
}
/**
*@returntheSystemMessage
*/
publicStringgetSystemMessage(){
returnSystemMessage;
}
}
C. java ssh 审批流程该怎么实现
实现思路如下:
1、建立用户权限机制,比较经典的角色-权限-用户
五张表的设计,你可以到网上查查,当用户在登陆时,获取登陆用户的ID;
2、通过该ID到权限系统中查询到他的权限菜单,交给用户展示出来,用户在操作的时候,去检测用户的权限是否能进行该项操作。