Pom.xml adding jar dependencies
<!--Https://mvnrepository.com/artifact/com.jcraft/jsch -<Dependency> <groupId>Com.jcraft</groupId> <Artifactid>Jsch</Artifactid> <version>0.1.54</version></Dependency>
Java class
PackageCom.aliyun.utility.jsch;Importcom.jcraft.jsch.ChannelExec;ImportCom.jcraft.jsch.JSch;Importcom.jcraft.jsch.Session;ImportJava.io.InputStream;Importjava.util.Properties; Public classJschutil {Private StaticJschutil instance; PrivateJschutil () {} Public Staticjschutil getinstance () {if(Instance = =NULL) {instance=NewJschutil (); } returninstance; } PrivateSession getsession (String host,intPort, String uesename)throwsException {Jsch Jsch=NewJsch (); Session Session=jsch.getsession (Uesename, host, Port); returnsession; } PublicSession Connect (String host,intport, String uesename, string password)throwsException {Session session=getsession (host, Port, Uesename); Session.setpassword (password); Properties Config=NewProperties (); Config.setproperty ("Stricthostkeychecking", "no"); Session.setconfig (config); Session.connect (); returnsession; } PublicString ExecCmd (Session session, String command)throwsException {if(Session = =NULL) { Throw NewRuntimeException ("Session is null!"); } channelexec exec= (channelexec) session.openchannel ("Exec"); InputStream in=Exec.getinputstream (); byte[] B =New byte[1024]; Exec.setcommand (command); Exec.connect (); StringBuffer Buffer=NewStringBuffer (); while(In.read (b) > 0) {buffer.append (NewString (b)); } exec.disconnect (); returnbuffer.tostring (); } Public voidClear (Session session) {if(Session! =NULL) &&session.isconnected ()) {Session.disconnect (); Session=NULL; } } Public Static voidMain (string[] args)throwsException {Session session=jschutil.getinstance (). Connect ("10.9.9.135", "yy", "yy"); String cmd= "CD/" + ";" + "Ls-al |grep Home"; String result= Jschutil.getinstance (). ExecCmd (session, CMD);// ???????;?? System.out.println (Result); System.exit (0); }}
Jsch Execute Linux command