Sometimes you may need to control the execution of Linux commands by code 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 FinalLogger log = Loggerfactory.getlogger (Cogradientimgfilemanager.class);Private StaticChannelexec channelexec;Private StaticSession session =NULL;Private Static intTimeout =60000;//test code Public Static void Main(string[] args) {Try{Versousshutil ("10.8.12.189","Jmuser","root1234", A); Runcmd ("Java-version","UTF-8"); }Catch(Exception e) {//TODO auto-generated catch blockE.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,intPortthrowsexception{Log.info ("Try to connect to .... Host:"+ Host +", Username:"+ UserName +", Password:"+ Password +", Port:"+ port); Jsch Jsch =NewJsch ();//Create Jsch ObjectSession = Jsch.getsession (UserName, host, Port);get a Session object based on username, host IP, PortSession.setpassword (password);//Set PasswordProperties config =NewProperties (); Config.put ("Stricthostkeychecking","No"); Session.setconfig (config);//Set properties for session objectSession.settimeout (timeout);//Set timeout timeSession.connect ();//Create links via session}/** * Execute command on remote server * @param cmd command string to execute * @param CharSet encoded * @throws exce ption * * Public Static void Runcmd(String cmd,string CharSet)throwsexception{channelexec = (channelexec) Session.openchannel ("Exec"); Channelexec.setcommand (CMD); Channelexec.setinputstream (NULL); Channelexec.seterrstream (System.err); Channelexec.connect (); InputStream in = Channelexec.getinputstream (); BufferedReader reader =NewBufferedReader (NewInputStreamReader (In, Charset.forname (Charset))); String buf =NULL; while((buf = Reader.readline ())! =NULL) {System.out.println (BUF); } reader.close (); Channelexec.disconnect (); }}
Jsch to connect a remote server to execute Linux commands in Java