Java代码调用服务器上的Shell脚本

这里主要是因为我们报表平台有用到用户手工录入的数据作为结果数据且需要纳入saiku去展示

如我们所知,saiku不会自动刷新,所以需要在数据更新接口中调用服务器上的shell脚本

话不多说,上代码: (直接使用Eclipse, run  Java Application ,执行成功后脚本中的输出内容会打印到控制台)

  1. package saikuDemo1;
  2.  
  3. import ch.ethz.ssh2.Connection;
  4. import ch.ethz.ssh2.Session;
  5. import ch.ethz.ssh2.StreamGobbler;
  6.  
  7. import java.io.*;
  8.  
  9. /**
  10. * 远程执行linux的shell script
  11. * @author Ickes
  12. * @author2 hpp
  13. * @since V0.2
  14. */
  15. public class RemoteExecuteCommand {
  16. //字符编码默认是utf-8
  17. private static String DEFAULTCHART="UTF-8";
  18. private static Connection conn;
  19. private String ip;
  20. private String userName;
  21. private String userPwd;
  22.  
  23. public RemoteExecuteCommand(String ip, String userName, String userPwd) {
  24. this.ip = ip;
  25. this.userName = userName;
  26. this.userPwd = userPwd;
  27. }
  28.  
  29. public RemoteExecuteCommand() {
  30.  
  31. }
  32.  
  33. /**
  34. * 远程登录linux的主机
  35. * @author Ickes
  36. * @since V0.1
  37. * @return
  38. * 登录成功返回true,否则返回false
  39. */
  40. public Boolean login(){
  41. boolean flg=false;
  42. try {
  43. conn = new Connection(ip);
  44. conn.connect();//连接
  45. flg=conn.authenticateWithPassword(userName, userPwd);//认证
  46. if (flg){
  47. System.out.println("认证成功!");
  48. }
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. return flg;
  53. }
  54. /**
  55. * @author Ickes
  56. * 远程执行shll脚本或者命令
  57. * @param cmd
  58. * 即将执行的命令
  59. * @return
  60. * 命令执行完后返回的结果值
  61. * @since V0.1
  62. */
  63. public String execute(String cmd){
  64. String result="";
  65. try {
  66. if(login()){
  67. Session session= conn.openSession();//打开一个会话
  68. session.execCommand(cmd);//执行命令
  69. result=processStdout(session.getStdout(),DEFAULTCHART);
  70. //如果为得到标准输出为空,说明脚本执行出错了
  71. if(result == null){
  72. result=processStdout(session.getStderr(),DEFAULTCHART);
  73. }
  74. conn.close();
  75. session.close();
  76. }
  77. } catch (IOException e) {
  78. e.printStackTrace();
  79. }
  80. return result;
  81. }
  82.  
  83. /**
  84. * @author Ickes
  85. * 远程执行shll脚本或者命令
  86. * @param cmd
  87. * 即将执行的命令
  88. * @return
  89. * 命令执行成功后返回的结果值,如果命令执行失败,返回空字符串,不是null
  90. * @since V0.1
  91. */
  92. public String executeSuccess(String cmd){
  93. String result="";
  94. try {
  95. if(login()){
  96. Session session= conn.openSession();//打开一个会话
  97. session.execCommand(cmd);//执行命令
  98. result=processStdout(session.getStdout(),DEFAULTCHART);
  99. conn.close();
  100. session.close();
  101. }
  102. } catch (IOException e) {
  103. e.printStackTrace();
  104. }
  105. return result;
  106. }
  107.  
  108. /**
  109. * 解析脚本执行返回的结果集
  110. * @author Ickes
  111. * @param in 输入流对象
  112. * @param charset 编码
  113. * @since V0.1
  114. * @return
  115. * 以纯文本的格式返回
  116. */
  117. public static String processStdout(InputStream in, String charset){
  118. InputStream stdout = new StreamGobbler(in);
  119. StringBuffer buffer = new StringBuffer();;
  120. try {
  121. BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));
  122. String line=null;
  123. while((line=br.readLine()) != null){
  124. buffer.append(line+"\n");
  125. }
  126. } catch (UnsupportedEncodingException e) {
  127. e.printStackTrace();
  128. } catch (IOException e) {
  129. e.printStackTrace();
  130. }
  131. return buffer.toString();
  132. }
  133.  
  134. public static void main(String[] args) {
  135.  
  136. RemoteExecuteCommand rec=new RemoteExecuteCommand("10.22.33.44", "root","root");// 参数分别为服务器IP ,用户名,密码
  137. //执行命令
  138. try {
  139. if(rec.login()){
  140.  
  141. System.out.println("=====第一个步骤=====");
  142. Session session= conn.openSession();//打开一个会话
  143. //TODO:多条命令
  144. session.execCommand("sh /app/Saiku/saikuRefreshShell.sh");//执行命令,这里需要确定刷新脚本存在的绝对路径哦
  145. String result=processStdout(session.getStdout(),DEFAULTCHART);
  146. //如果为得到标准输出为空,说明脚本执行出错了
  147. if(result == null){
  148. System.out.println("脚本出错");
  149. result=processStdout(session.getStderr(),DEFAULTCHART);
  150. }
  151. System.out.println(result);
  152. session.close();
  153.  
  154. /**
  155. System.out.println("=====第二个步骤=====");
  156. Session session2= conn.openSession();//打开一个会话
  157. //TODO:多条命令
  158. session2.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim/result;cat xyy_result_m10d.json");//执行命令
  159. String result2=processStdout(session2.getStdout(),DEFAULTCHART);
  160. //如果为得到标准输出为空,说明脚本执行出错了
  161. if(result == null ){//StringUtils.isBlank(result2)
  162. System.out.println("脚本出错");
  163. result2=processStdout(session2.getStderr(),DEFAULTCHART);
  164. }
  165. System.out.println(result2);
  166. session2.close();
  167. */
  168.  
  169. conn.close();
  170. }
  171. } catch (IOException e) {
  172. e.printStackTrace();
  173. }
  174.  
  175. }
  176.  
  177. public static void setCharset(String charset) {
  178. DEFAULTCHART = charset;
  179. }
  180. public Connection getConn() {
  181. return conn;
  182. }
  183. public void setConn(Connection conn) {
  184. this.conn = conn;
  185. }
  186. public String getIp() {
  187. return ip;
  188. }
  189. public void setIp(String ip) {
  190. this.ip = ip;
  191. }
  192. public String getUserName() {
  193. return userName;
  194. }
  195. public void setUserName(String userName) {
  196. this.userName = userName;
  197. }
  198. public String getUserPwd() {
  199. return userPwd;
  200. }
  201. public void setUserPwd(String userPwd) {
  202. this.userPwd = userPwd;
  203. }
  204. }

  

Java代码调用服务器上的Shell脚本的更多相关文章

  1. java调用机器上的shell脚本

    java调用机器上的shell脚本,可以这样方便的通过shell脚本调用本机的C.C++等程序 Process process = null; Runtime runTime = Runtime.ge ...

  2. Java程序调用带参数的shell脚本返回值

    Java程序调用带参数的shell脚本返回值 首先来看看linux中shell变量(\(#,\)@,$0,$1,\(2)的含义解释 变量说明: -  \)$  Shell本身的PID(ProcessI ...

  3. java远程执行linux服务器上的shell脚本

    业务场景:需要从服务器A中新增的文件同步至本地服务器,服务器A中内存有限,需同步成功之后清除文件. Java调用远程shell脚本,需要和远程服务器建立ssh链接,再调用指定的shell脚本. 1.创 ...

  4. 通过Jenkins调用自动部署war包及jar包到服务器上的Shell脚本

    1)部署war包#!/bin/bashif [ id>0];then echo"stopproject" kill −9 idelse echo "project ...

  5. Java代码调用Shell脚本并传入参数实现DB2数据库表导出到文件

    本文通过Java代码调用Shell脚本并传入参数实现DB2数据库表导出到文件,代码如下: import java.io.File; import java.io.IOException; import ...

  6. java远程调用linux的命令或者脚本

    转载自:http://eksliang.iteye.com/blog/2105862 Java通过SSH2协议执行远程Shell脚本(ganymed-ssh2-build210.jar) 使用步骤如下 ...

  7. linux 执行远程linux上的shell脚本或者命令以及scp 上传文件到ftp--免密码登陆

    场景:在linux A 上执行Linux B上的shell脚本和命令 步骤1.设置ssh免登陆 1.SSH无密码登录 # 本地服务器执行(A机器):生成密钥对 ssh-keygen -t dsa -P ...

  8. Java代码调用Oracle的存储过程,存储函数和包

    Java代码调用存储过程和存储函数要使用CallableStatement接口 查看API文档: 上代码: java代码调用如下的存储过程和函数: 查询某个员工的姓名  月薪 职位 create or ...

  9. windows下上传shell脚本不能运行—将dos模式修改为unix 文件格式

    windows下上传shell脚本至linux,其格式将为dos.dos模式的shell脚本将不能再linux下正确运行,需要修改文件模式为unix. 1 查看文件模式方法 linux服务器上,用vi ...

随机推荐

  1. Linux命令-cut篇

    Cut 命令是常用的 Linux 命令,在这里总结一下平时常用的参数和用法,方便查证. 常用参数: -b:以字节为单位进行分割: -c:以字符为单位进行分割: -d:自定义分割符进行分割,默认为制表符 ...

  2. UI自动化(十四)yaml配置文件

    import yamlimport jsonf = open('config.yaml','rb')data = yaml.load(f)print(json.dumps(data,indent=4) ...

  3. 【Alpha】Scrum Meeting 11

    目录 前言 任务分配 燃尽图 会议照片 签入记录 前言 第11次会议于4月16日18:15在一公寓三楼召开. 交流确认了任务进度,讨论项目发布事宜,分配下一阶段任务.时长45min. 任务分配 姓名 ...

  4. 将markdown文档使用gulp转换为HTML【附带两套css样式】

    将markdown文档使用gulp转换为HTML[附带两套css样式] 今天遇到一个需求,即将Markdown文档转为为HTML在网页展示,身为一名程序员,能用代码解决的问题,手动打一遍无疑是可耻的. ...

  5. Autowired(required=true)

    问题原因 没有实现类的接口上添加了@Autowired注解 问题解决 删掉@Autowired注解 bug详情 Description: Field userDAO in com.crab.servi ...

  6. 出错:(unicode error) 'unicodeescape' codec can't decode bytes in position 8-9: malformed \N character escape

    报错原因:python 中 \N 是换行的意思.这里要把 N 前面的 \ 转义一下.用  \\  代替即可. Nokia_mac = np.loadtxt('data\oui\\NokiaMac201 ...

  7. 【书】.NET及计算机类相关书籍,持续更新...

    一级目录 链接: https://pan.baidu.com/s/1y3osr3YCQ7XlM81RzkN1eQ 提取码: gs3r 二级目录 链接: https://pan.baidu.com/s/ ...

  8. C++_day8_ 多重继承、钻石继承和虚继承

    1.继承的复习 1.1 类型转换 编译器认为访问范围缩小是安全的. 1.2 子类的构造与析构 子类中对基类构造函数初始化只能写在初始化表里,不能写在函数体中. 阻断继承. 1.3 子类的拷贝构造与拷贝 ...

  9. php-fpm开启慢查询日志

    php-fpm.conf /usr/local/php/etc/php-fpm.conf 开启慢查询日志 ; The log file for slow requests ; Default Valu ...

  10. Node.js进程内存使用查看方法及返回对象的含义

    1 前言 使用process.memoryUsage() ,然后可以得到一个对象如下: var mem = process.memoryUsage(); console.log(mem); 结果: { ...