zoukankan      html  css  js  c++  java
  • java远程调用linux的命令或者脚本

    转载自:http://eksliang.iteye.com/blog/2105862

     Java通过SSH2协议执行远程Shell脚本(ganymed-ssh2-build210.jar) 

     使用步骤如下:

    一、导ganymed-ssh2-build210.jar包

    
    
    1. <!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
    2.  <dependency>
    3.  <groupId>ch.ethz.ganymed</groupId>
    4.  <artifactId>ganymed-ssh2</artifactId>
    5.  <version>build210</version>
    6.  </dependency>

    二、API说明

    1.  首先构造一个连接器,传入一个需要登陆的ip地址

    Connection conn = new Connection(hostname);

    2.  模拟登陆目的服务器 传入用户名和密码 

    
    
    1. //它会返回一个布尔值,true 代表成功登陆目的服务器,否则登陆失败
    2. boolean isAuthenticated = conn.authenticateWithPassword(username, password);​

    3.  打开一个session,有点象hibernate的session ,执行你需要的Linux 脚本命令 。

    
    
    1. Session sess = conn.openSession();
    2. sess.execCommand("last");​

    4. 接收目标服务器上的控制台返回结果,读取br中的内容

    
    
    1. InputStream stdout =newStreamGobbler(sess.getStdout());
    2. BufferedReader br =newBufferedReader(newInputStreamReader(stdout));​

    5.得到脚本运行成功与否的标志 :0-成功 非0-失败

    
    
    1. System.out.println("ExitCode: "+ sess.getExitStatus());​

    6.关闭session和connection

    
    
    1.  sess.close();
    2.  conn.close();​

     

    备注:

    1.通过第2步认证成功后,当前目录就位于/home/username/目录之下,你可以指定脚本文件所在的绝对路径,或者通过cd导航到脚本文件所在的目录,然后传递执行脚本所需要的参数,完成脚本调用执行。

     

    2.执行脚本以后,可以获取脚本执行的结果文本,需要对这些文本进行正确编码后返回给客户端,避免乱码产生。

     

    3.如果你需要执行多个linux控制台脚本,比如第一个脚本的返回结果是第二个脚本的入参,你必须打开多个Session,也就是多次调用

    Session sess = conn.openSession();,使用完毕记得关闭就可以了

     

    三、实例代码,这个类可以直接拷贝过去用

    
    
    1. import java.io.BufferedReader;
    2. import java.io.IOException;
    3. import java.io.InputStream;
    4. import java.io.InputStreamReader;
    5. import java.io.UnsupportedEncodingException;
    6. import org.apache.commons.lang.StringUtils;
    7. import ch.ethz.ssh2.Connection;
    8. import ch.ethz.ssh2.Session;
    9. import ch.ethz.ssh2.StreamGobbler;
    10. /**
    11. * 远程执行linux的shell script
    12. * @author Ickes
    13. * @since V0.1
    14. */
    15. publicclassRemoteExecuteCommand{
    16. //字符编码默认是utf-8
    17. privatestaticString DEFAULTCHART="UTF-8";
    18. privateConnection conn;
    19. privateString ip;
    20. privateString userName;
    21. privateString userPwd;
    22. publicRemoteExecuteCommand(String ip,String userName,String userPwd){
    23. this.ip = ip;
    24. this.userName = userName;
    25. this.userPwd = userPwd;
    26. }
    27. publicRemoteExecuteCommand(){
    28. }
    29. /**
    30. * 远程登录linux的主机
    31. * @author Ickes
    32. * @since V0.1
    33. * @return
    34. * 登录成功返回true,否则返回false
    35. */
    36. publicBoolean login(){
    37. boolean flg=false;
    38. try{
    39. conn =newConnection(ip);
    40. conn.connect();//连接
    41. flg=conn.authenticateWithPassword(userName, userPwd);//认证
    42. }catch(IOException e){
    43. e.printStackTrace();
    44. }
    45. return flg;
    46. }
    47. /**
    48. * @author Ickes
    49. * 远程执行shll脚本或者命令
    50. * @param cmd
    51. * 即将执行的命令
    52. * @return
    53. * 命令执行完后返回的结果值
    54. * @since V0.1
    55. */
    56. publicString execute(String cmd){
    57. String result="";
    58. try{
    59. if(login()){
    60. Session session= conn.openSession();//打开一个会话
    61. session.execCommand(cmd);//执行命令
    62. result=processStdout(session.getStdout(),DEFAULTCHART);
    63. //如果为得到标准输出为空,说明脚本执行出错了
    64. if(StringUtils.isBlank(result)){
    65. result=processStdout(session.getStderr(),DEFAULTCHART);
    66. }
    67. conn.close();
    68. session.close();
    69. }
    70. }catch(IOException e){
    71. e.printStackTrace();
    72. }
    73. return result;
    74. }
    75. /**
    76. * @author Ickes
    77. * 远程执行shll脚本或者命令
    78. * @param cmd
    79. * 即将执行的命令
    80. * @return
    81. * 命令执行成功后返回的结果值,如果命令执行失败,返回空字符串,不是null
    82. * @since V0.1
    83. */
    84. publicString executeSuccess(String cmd){
    85. String result="";
    86. try{
    87. if(login()){
    88. Session session= conn.openSession();//打开一个会话
    89. session.execCommand(cmd);//执行命令
    90. result=processStdout(session.getStdout(),DEFAULTCHART);
    91. conn.close();
    92. session.close();
    93. }
    94. }catch(IOException e){
    95. e.printStackTrace();
    96. }
    97. return result;
    98. }
    99. /**
    100. * 解析脚本执行返回的结果集
    101. * @author Ickes
    102. * @param in 输入流对象
    103. * @param charset 编码
    104. * @since V0.1
    105. * @return
    106. * 以纯文本的格式返回
    107. */
    108. privateString processStdout(InputStreamin,String charset){
    109. InputStream stdout =newStreamGobbler(in);
    110. StringBuffer buffer =newStringBuffer();;
    111. try{
    112. BufferedReader br =newBufferedReader(newInputStreamReader(stdout,charset));
    113. String line=null;
    114. while((line=br.readLine())!=null){
    115. buffer.append(line+" ");
    116. }
    117. }catch(UnsupportedEncodingException e){
    118. e.printStackTrace();
    119. }catch(IOException e){
    120. e.printStackTrace();
    121. }
    122. return buffer.toString();
    123. }
    124. publicstaticvoid setCharset(String charset){
    125. DEFAULTCHART = charset;
    126. }
    127. publicConnection getConn(){
    128. return conn;
    129. }
    130. publicvoid setConn(Connection conn){
    131. this.conn = conn;
    132. }
    133. publicString getIp(){
    134. return ip;
    135. }
    136. publicvoid setIp(String ip){
    137. this.ip = ip;
    138. }
    139. publicString getUserName(){
    140. return userName;
    141. }
    142. publicvoid setUserName(String userName){
    143. this.userName = userName;
    144. }
    145. publicString getUserPwd(){
    146. return userPwd;
    147. }
    148. publicvoid setUserPwd(String userPwd){
    149. this.userPwd = userPwd;
    150. }
    151. }

     测试代码:

     

    
    
    1.  publicstaticvoid main(String[] args){
    2. RemoteExecuteCommand rec=newRemoteExecuteCommand("192.168.168.200","root","123456");
    3. //执行命令
    4. System.out.println(rec.execute("ifconfig"));
    5. //执行脚本
    6. rec.execute("sh /usr/local/tomcat/bin/statup.sh");
    7. //这个方法与上面最大的区别就是,上面的方法,不管执行成功与否都返回,
    8. //这个方法呢,如果命令或者脚本执行错误将返回空字符串
    9. rec.executeSuccess("ifconfig");
    10. }

     

     需要导入的包:

     

    
    
    1. <!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
    2. <dependency>
    3. <groupId>ch.ethz.ganymed</groupId>
    4. <artifactId>ganymed-ssh2</artifactId>
    5. <version>build210</version>
    6. </dependency>
    7.  
    8. <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    9. <dependency>
    10. <groupId>commons-io</groupId>
    11. <artifactId>commons-io</artifactId>
    12. <version>2.5</version>
    13. </dependency>
    14.  
    15. <dependency>
    16. <groupId>commons-lang</groupId>
    17. <artifactId>commons-lang</artifactId>
    18. <version>2.6</version>
    19. <type>jar</type>
    20. <scope>compile</scope>
    21. </dependency>

     

     

     

    如果是直接通过导jar包的,附百度云盘下载地址:链接:http://pan.baidu.com/s/1c2dr34 密码:g3l7

     

    四、注意事项

    执行命令的时候,比如:jps,Linux系统因为有环境变量,所以命令正确。但是如果是在java中远程调用Linux命令,

    那么必须使用绝对路径,如:/usr/local/java/jdk1.8/bin/jps

     
  • 相关阅读:
    BNU 51002 BQG's Complexity Analysis
    BNU OJ 51003 BQG's Confusing Sequence
    BNU OJ 51000 BQG's Random String
    BNU OJ 50999 BQG's Approaching Deadline
    BNU OJ 50998 BQG's Messy Code
    BNU OJ 50997 BQG's Programming Contest
    CodeForces 609D Gadgets for dollars and pounds
    CodeForces 609C Load Balancing
    CodeForces 609B The Best Gift
    CodeForces 609A USB Flash Drives
  • 原文地址:https://www.cnblogs.com/yangcx666/p/8723868.html
Copyright © 2011-2022 走看看