当前位置:   article > 正文

远程连接linux或者本地执行shell_windows远程执行linux脚本

windows远程执行linux脚本

远程连接linux或者本地执行shell,单例模式

  1. import ch.ethz.ssh2.Connection;
  2. import ch.ethz.ssh2.Session;
  3. import ch.ethz.ssh2.StreamGobbler;
  4. import com.alibaba.druid.util.StringUtils;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.io.UnsupportedEncodingException;
  12. /**
  13. * @ClassName: RemoteConnection
  14. * @Description: TODO
  15. * @Author Tan
  16. * @Date 2019/7/27
  17. */
  18. public class RemoteConnection {
  19. private final static Logger log = LoggerFactory.getLogger(RemoteConnection.class);
  20. private static RemoteConnection instance;
  21. private static String DEFAULTCHART = "UTF-8";
  22. private static Connection conn = null;
  23. private static String SERVER = "linux";
  24. private static String IP = "192.168.1.2";
  25. private static String HOST_NAME = "root";
  26. private static String HOST_PWD = "123456";
  27. public static synchronized RemoteConnection getInstance() {
  28. if (instance == null) {
  29. instance = new RemoteConnection();
  30. }
  31. return instance;
  32. }
  33. public static synchronized Connection getCon(String ip, String userName, String userPwd) {
  34. if (conn == null) {
  35. conn = login(ip, userName, userPwd);
  36. }
  37. return conn;
  38. }
  39. /**
  40. * 登录主机
  41. *
  42. * @return 登录成功返回true,否则返回false
  43. */
  44. public static Connection login(String ip, String userName, String userPwd) {
  45. boolean flg = false;
  46. Connection conn = null;
  47. try {
  48. conn = new Connection(ip);
  49. conn.connect();
  50. flg = conn.authenticateWithPassword(userName, userPwd);//认证
  51. if (flg) {
  52. log.debug("登录成功" + conn);
  53. return conn;
  54. }
  55. } catch (IOException e) {
  56. log.debug("登录失败" + e.getMessage());
  57. e.printStackTrace();
  58. }
  59. return conn;
  60. }
  61. /**
  62. * 远程执行shll脚本或者命令 使用默认的cmd文件
  63. *
  64. * @param cmd 即将执行的命令
  65. * @return 命令执行完后返回的结果值
  66. */
  67. public static String execute(String cmd, String ip, String host, String pwd) {
  68. String result = "";
  69. Connection conn = getCon(ip, host, pwd);
  70. try {
  71. if (conn != null) {
  72. Session session = conn.openSession();//打开一个会话
  73. session.execCommand(cmd);//执行命令
  74. result = processStdout(session.getStdout(), DEFAULTCHART);
  75. //如果为得到标准输出为空,说明脚本执行出错了
  76. if (StringUtils.isEmpty(result)) {
  77. log.debug("得到标准输出为空, 链接conn:" + conn + ",执行的命令:" + cmd);
  78. result = processStdout(session.getStderr(), DEFAULTCHART);
  79. } else {
  80. log.debug("执行命令成功, 链接conn:" + conn + ",执行的命令:" + cmd);
  81. }
  82. session.close();
  83. }
  84. } catch (IOException e) {
  85. log.debug("执行命令失败,链接conn:" + conn + ",执行的命令:" + cmd + " " + e.getMessage());
  86. e.printStackTrace();
  87. }
  88. return result;
  89. }
  90. /**
  91. * 解析脚本执行返回的结果集
  92. *
  93. * @param in 输入流对象
  94. * @param charset 编码
  95. * @return 以纯文本的格式返回
  96. */
  97. private static String processStdout(InputStream in, String charset) {
  98. InputStream stdout = new StreamGobbler(in);
  99. StringBuffer buffer = new StringBuffer();
  100. ;
  101. try {
  102. BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
  103. String line = null;
  104. while ((line = br.readLine()) != null) {
  105. buffer.append(line + "\n");
  106. }
  107. } catch (UnsupportedEncodingException e) {
  108. log.error("解析脚本出错:" + e.getMessage());
  109. e.printStackTrace();
  110. } catch (IOException e) {
  111. log.error("解析脚本出错:" + e.getMessage());
  112. e.printStackTrace();
  113. }
  114. return buffer.toString();
  115. }
  116. /**
  117. * 执行本地linux命令
  118. * 部署到linuxs时不需要登录,直接调此方法执行
  119. * @param cmd
  120. * @return
  121. */
  122. public static String execCommand(String cmd) {
  123. String result = "";
  124. String[] cmds = new String[]{"sh", "-c", cmd};
  125. try {
  126. Runtime rt = Runtime.getRuntime();
  127. Process proc = rt.exec(cmds);
  128. result = processStdout(proc.getInputStream(), DEFAULTCHART);
  129. //如果为得到标准输出为空,说明脚本执行出错了
  130. if (StringUtils.isEmpty(result)) {
  131. log.debug("执行的命令无结果:" + cmd);
  132. } else {
  133. log.debug("执行命令成功, 执行的命令:" + cmd);
  134. }
  135. } catch (Exception e) {
  136. log.debug("执行命令失败,执行的命令:" + cmd + " " + e.getMessage());
  137. e.printStackTrace();
  138. }
  139. return result;
  140. }
  141. public static void main(String[] args) {
  142. String cmd = "ps aux | grep tomcat | grep -v grep";
  143. String execute = null;
  144. if ("Linux".equalsIgnoreCase(SERVER)) {
  145. execute = RemoteConnection.getInstance().execCommand(cmd); //linux
  146. } else {
  147. execute = RemoteConnection.getInstance().execute(cmd, IP, HOST_NAME, HOST_PWD);//Windows远程调用执行
  148. }
  149. log.info(execute);
  150. }
  151. }

其中有个坑

就是执行复杂命令时如:ps -ef|grep tomcat  时

 Process proc = rt.exec(cmd); 执行无结果返回

必须将命令转成数组形式

  1. String[] cmds = new String[]{"sh", "-c", cmd};
  2. Process proc = rt.exec(cmds);


 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/840795
推荐阅读
相关标签
  

闽ICP备14008679号