Sometimes you might want to use code to control the execution of Linux commands to implement certain functions.
For this type of problem can be implemented using Jsch, the specific code is as follows:
public class cogradientimgfilemanager{private static final Logger log = Loggerfactory.getlogger (
Cogradientimgfilemanager.class);
private static channelexec channelexec;
private static Session session = NULL;
private static int timeout = 60000; Test code public static void Main (string[] args) {try{versousshutil ("10.8.12.189", "Jmuser", "root1234"); Runcmd ("Java-
Version "," UTF-8 ");
}catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();}} /** * Connect remote server * @param host IP address * @param userName login * @param password Password * @param port * @throws Exception/Public static void Versousshutil (String host,string username,string password,int Port) throws exception{("Attempt to connect to ....
Host: "+ Host +", Username: "+ username +", password: "+ password +", Port: "+ port"; Jsch Jsch = new Jsch (); Create Jsch Object session = Jsch.getsession (UserName, host, Port); According to user name, host IP, port to obtain a Session object Session.setpassword (password);
Set Password Properties config = new properties (); Config.put ("StRicthostkeychecking "," no "); Session.setconfig (config); Sets the properties Session.settimeout (timeout) for the session object; Set timeout time session.connect (); Create a link through session/** * Execute command on remote server * @param cmd the command string to execute * @param charset encoding * @throws Exception/public static void
Runcmd (String cmd,string charset) throws exception{Channelexec = (channelexec) session.openchannel ("exec");
Channelexec.setcommand (CMD);
Channelexec.setinputstream (NULL);
Channelexec.seterrstream (System.err);
Channelexec.connect ();
InputStream in = Channelexec.getinputstream ();
BufferedReader reader = new BufferedReader (new InputStreamReader (In, Charset.forname (Charset));
String buf = null;
while ((buf = Reader.readline ())!= null) {System.out.println (BUF);} reader.close ();
Channelexec.disconnect (); }
}