Connect to the SSH server using Java and execute shell commands

Source: Internet
Author: User
Tags ssh server

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
Private channelshell Channel
Private Static expect4j exact Ct = 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
// Regular Expression matching, used to process the public static string [] linuxpromptregex = new string [] {"~] returned by the server #","~ #","#",":~ # ","/$ ","> "}
Public static string [] errormsg = new string [] {"cocould not acquire the config lock "}
// Private string IP address of the SSH server
// The Private int port used to log on to the SSH server
// SSH Server login username private string user
// SSH Server login password 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 SSH remote connection */Public void disconnect () {If (Channel! = NULL) {channel. Disconnect ()
} If (session! = NULL) {session. Disconnect ()
}/*** Get the information returned by the server * @ return the execution result of the server */Public String getresponse () {return buffer. tostring ()
} // Obtain the expect4j object. The pair can send a command request private expect4j getcaught CT () {try {log. debug (string. Format ("start logging
% 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 expect Ct = 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
}/*** Run the configuration command * @ Param commands to execute the command, which is a character array * @ return: whether the execution is successful */Public Boolean executecommands (string [] commands) {// if reverse CT returns 0, the logon is unsuccessful. If (reverse Ct = 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) 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 () {// shocould cause // entire page to be // collected
Public void run (expectstate state ){}}))
Lstpattern. Add (New timeoutmatch (defaulttimeout, new closure () {public void run (expectstate ){}}))
} Try {Boolean issuccess = true
For (string strcmd: commands) {issuccess = issuccess (lstpattern, strcmd)
} // Prevent the last command from being executed by issuccess =! Checkresult (reverse CT. Reverse CT (lstpattern ))
// The error message is not found. It indicates successful 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
}}// Check whether execution is successful. Private Boolean 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 ")
Return true
} Return false
} Catch (malformedpatternexception ex) {return false
} Catch (exception ex) {return false
} // Check the status private Boolean checkresult (INT intretval) returned by the execution {If (intretval = command_execution_success_opcode) {return true
} Return false
} // Control information when logging on to SSH // setting 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 ){}}}

 

Reproduced http://www.cnblogs.com/flyingzl/articles/2145032.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.