欢迎来到天天文库
浏览记录
ID:32366518
大小:52.03 KB
页数:3页
时间:2019-02-03
《java执行shell命令代码亲测可用》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、Java执行shell命令代码亲测可用1.packagecom.qin.shell;2. 3.importjava.io.BufferedReader;4.importjava.io.IOException;5.importjava.io.InputStream;6.importjava.io.InputStreamReader;7. 8.importorg.mortbay.log.Log;9. 10.importch.ethz.ssh2.Connection;11.importch.ethz.ssh2.Session;12.importch.ethz.ssh2.StreamGobbler;1
2、3. 14.publicclassExecShell{15.privateStringIP;//要远程登录的IP地址16.privateStringusername;//用户名17.privateStringpassword;//密码18. 19.publicExecShell(StringIP,Stringusername,Stringpassword){20.this.IP=IP;21.this.username=username;22.this.password=password;23.}24. 25.//命令执行26.publicbooleanexec(Stringcommand)th
3、rowsInterruptedException{27.Log.info("command:"+command);28.booleanrtn=false;29.try{30.Connectionconn=newConnection(IP);31.conn.connect();32.booleanisAuthenticated=conn.authenticateWithPassword(username,password);33.if(isAuthenticated==false){34.thrownewIOException("Authenticationfailed.");35.}36.Se
4、ssionsess=conn.openSession();37.sess.execCommand(command);38. 39.InputStreamstdout=newStreamGobbler(sess.getStdout());1.BufferedReaderbr=newBufferedReader(newInputStreamReader(stdout));2. 3.InputStreamstderr=newStreamGobbler(sess.getStderr());4.BufferedReaderstderrReader=newBufferedReader(newInputSt
5、reamReader(stderr));5. 6.Stringline=null;7.while((line=br.readLine())!=null)8.{9.Log.info("GanyMedUtilout>"+line);10.}11. 12.while(true)13.{14.line=stderrReader.readLine();15.if(line==null)16.break;17.Log.info("GanyMedUtilout>"+line);18.}19. 20./*Showexitstatus,ifavailable(otherwise"null")*/21
6、.Log.info("ExitCode:"+sess.getExitStatus()+""+IP+":"+command);22.sess.close();23.conn.close();24.rtn=newInteger(0).equals(sess.getExitStatus());25.returnrtn;26.}27.catch(IOExceptione)28.{29.Log.warn("Error......................",e);30.e.printStackTrace();31.System.exit(2);32.returnrtn;33.}34.}35. 36
7、.publicstaticvoidmain(String[]args)throwsInterruptedException{37. 38.ExecShelles=newExecShell("192.168.75.130","root","dongliang");1.System.out.println("==========================================单个命令测
此文档下载收益归作者所有