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;
Publicclass shell {
Privatestatic logger log = logger. getlogger (shell. Class );
Private session;
Private channelshell channel;
Privatestatic expect4j exact Ct = NULL;
Privatestaticfinallong defaulttimeout = 1000;
Private stringbuffer buffer = new stringbuffer ();
Publicstaticfinalint command_execution_success_opcode =-2;
Publicstaticfinal string backslash_r = "\ r ";
Publicstaticfinal string backslash_n = "\ n ";
Publicstaticfinal string colon_char = ":";
Publicstatic string enter_character = backslash_r;
Publicstaticfinalint ssh_port = 22;
// Regular Expression matching, used to process the results returned by the server
Publicstatic string [] linuxpromptregex = new string [] {"~] #","~ #","#",
":~ # ","/$ ","> "};
Publicstatic string [] errormsg = new string [] {"cocould not acquire the config lock "};
// Ip address of the SSH server
Private string IP;
// The logon port of the SSH server
Privateint port;
// Login username of the SSH server
Private string user;
// Logon password of the SSH server
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;
Reverse Ct = getreverse CT ();
}
/**
* Close the SSH remote connection
*/
Publicvoid disconnect (){
If (Channel! = NULL ){
Channel. Disconnect ();
}
If (session! = NULL ){
Session. Disconnect ();
}
}
/**
* Get the information returned by the server
* @ Return indicates the execution result of the server.
*/
Public String getresponse (){
Return buffer. tostring ();
}
// Obtain the expect4j object, which can send command requests to SSH
Private expect4j getexpect (){
Try {
Log. debug (string. Format ("start logging to % s @ % s: % s", user, IP, Port ));
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 exact Ct = new expect4j (Channel. getinputstream (), Channel
. Getoutputstream ());
Channel. Connect ();
Log. debug (string. Format ("logging to % s @ % s: % s successfully! ", User, IP, Port ));
Return repeated CT;
} Catch (exception ex ){
Log. Error ("connect to" + IP + ":" + port + "failed, please check your username and password! ");
Ex. printstacktrace ();
}
Returnnull;
}
/**
* Execute the configuration command
* @ Param commands refers to the command to be executed, which is a character array
* @ Return: whether the execution is successful
*/
Publicboolean executecommands (string [] commands ){
// If reverse CT returns 0, the logon is unsuccessful.
If (distinct Ct = NULL ){
Returnfalse;
}
Log. debug ("---------- running commands are listed as follows :----------");
For (string command: commands ){
Log. debug (command );
}
Log. debug ("---------- END ----------");
Closure closure = new closure (){
Publicvoid run (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 ){
Returnfalse;
} Catch (exception e ){
Returnfalse;
}
}
Lstpattern. Add (New eofmatch (new closure () {// shocould cause
// Entire page to be
// Collected
Publicvoid run (expectstate state ){
}
}));
Lstpattern. Add (New timeoutmatch (defaulttimeout, new closure (){
Publicvoid run (expectstate state ){
}
}));
}
}
Try {
Boolean issuccess = true;
For (string strcmd: commands ){
Issuccess = issuccess (lstpattern, strcmd );
}
// Prevent the last command from being executed
Issuccess =! Checkresult (reverse CT. Reverse CT (lstpattern ));
// The error message cannot be found, indicating that the request is successful.
String response = buffer. tostring (). tolowercase ();
For (string MSG: errormsg ){
If (response. indexof (MSG)>-1 ){
Returnfalse;
}
}
Return issuccess;
} Catch (exception ex ){
Ex. printstacktrace ();
Returnfalse;
}
}
// Check whether execution is successful
Privateboolean issuccess (list <match> objpattern, string strcommandpattern ){
Try {
Boolean isfailed = checkresult (reverse CT. Reverse CT (objpattern ));
If (! Isfailed ){
Reverse CT. Send (strcommandpattern );
Reverse CT. Send ("\ r ");
Returntrue;
}
Returnfalse;
} Catch (malformedpatternexception ex ){
Returnfalse;
} Catch (exception ex ){
Returnfalse;
}
}
// Check the status returned by the execution
Privateboolean checkresult (INT intretval ){
If (intretval = command_execution_success_opcode ){
Returntrue;
}
Returnfalse;
}
// Control information for logging on to SSH
// You are not prompted to enter the password or display the logon information.
Publicstaticclass localuserinfo implements userinfo {
String passwd;
Public String GetPassword (){
Return passwd;
}
Publicboolean promptyesno (string Str ){
Returntrue;
}
Public String getpassphrase (){
Returnnull;
}
Publicboolean promptpassphrase (string message ){
Returntrue;
}
Publicboolean promptpassword (string message ){
Returntrue;
}
Publicvoid showmessage (string message ){
}
}
}