【原】Java程序调用远程Shell脚本
此程序的目的是执行远程机器上的Shell脚本。
【环境参数】
远程机器IP:192.168.234.123
用户名:root
密码:root
Shell脚本的路径:/home/IFileGenTool/BakProvisionAndOccurEntrance.sh
【具体步骤】
1、在远程机器上,准备Shell脚本。
[root@localhost IFileGenTool]# vim ./load_data.sh
#!/bin/sh
source /etc/profile
dbName=$
tableName=$
echo [`date +'%Y-%m-%d %H:%M:%S'`]' start loading data...'
mysql -uroot -p123456 -P3306 ${dbName} -e "LOAD DATA LOCAL INFILE '/home/IFileGenTool/bak_data/bak_data_bak.txt' INTO TABLE ${tableName} FIELDS TERMINATED BY ';'"
echo [`date +'%Y-%m-%d %H:%M:%S'`]' end loading data...'
exit
EOF
2、导入需要依赖的jar包。
Java远程调用Shell脚本这个程序需要ganymed-ssh2-build210.jar包。
下载地址:http://www.ganymed.ethz.ch/ssh2/
为了调试方便,可以将\ganymed-ssh2-build210\src下的代码直接拷贝到我们的工程里,
此源码的好处就是没有依赖很多其他的包,拷贝过来干干净净。
<dependency>
<groupId>org.jvnet.hudson</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210-hudson-1</version>
</dependency>
3、编写RemoteShellExecutor工具类。
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler; public class RemoteShellExecutor { private Connection conn;
/** 远程机器IP */
private String ip;
/** 用户名 */
private String osUsername;
/** 密码 */
private String password;
private String charset = Charset.defaultCharset().toString(); private static final int TIME_OUT = 1000 * 5 * 60; /**
* 构造函数
* @param ip
* @param usr
* @param pasword
*/
public RemoteShellExecutor(String ip, String usr, String pasword) {
this.ip = ip;
this.osUsername = usr;
this.password = pasword;
} /**
* 登录
* @return
* @throws IOException
*/
private boolean login() throws IOException {
conn = new Connection(ip);
conn.connect();
return conn.authenticateWithPassword(osUsername, password);
} /**
* 执行脚本
*
* @param cmds
* @return
* @throws Exception
*/
public int exec(String cmds) throws Exception {
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
int ret = -1;
try {
if (login()) {
// Open a new {@link Session} on this connection
Session session = conn.openSession();
// Execute a command on the remote machine.
session.execCommand(cmds); stdOut = new StreamGobbler(session.getStdout());
outStr = processStream(stdOut, charset); stdErr = new StreamGobbler(session.getStderr());
outErr = processStream(stdErr, charset); session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT); System.out.println("outStr=" + outStr);
System.out.println("outErr=" + outErr); ret = session.getExitStatus();
} else {
throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
}
} finally {
if (conn != null) {
conn.close();
}
IOUtils.closeQuietly(stdOut);
IOUtils.closeQuietly(stdErr);
}
return ret;
} /**
* @param in
* @param charset
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
private String processStream(InputStream in, String charset) throws Exception {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
return sb.toString();
} public static void main(String args[]) throws Exception {
RemoteShellExecutor executor = new RemoteShellExecutor("192.168.234.123", "root", "beebank");
// 执行myTest.sh 参数为java Know dummy
System.out.println(executor.exec("/home/IFileGenTool /load_data.sh t_users myDataBase01"));
}
}
4、Java程序调用远程Shell
private void backupAndRestoreData(String originalTableName) throws Exception {
//1. 调用远程Shell脚本,对生产库中数据进行导出和导入备份。
LogUtil.getLogger().info("###### 1. 开始对数据库中数据利用进行导出和导入备份 ######");
RemoteShellExecutor executor = new RemoteShellExecutor("192.168.234.123", "root", "root");
// 执行myTest.sh 参数为java Know dummy
System.out.println(executor.exec("/home/IFileGenTool/load_data.sh"));
}
5、运行结果
备份数据成功。
6、说明:
0 // getExitStatus方法的返回值
注:一般情况下shell脚本正常执行完毕,getExitStatus方法返回0。
此方法通过远程命令取得Exit Code/status。但并不是每个server设计时都会返回这个值,如果没有则会返回null。
在调用getExitStatus时,要先调用WaitForCondition方法,通过ChannelCondition.java接口的定义可以看到每个条件的具体含义。见以下代码:
ChannelCondition.java的源代码
参考连接:http://yu.you163.blog.163.com/blog/static/339877742012117101039968/
【原】Java程序调用远程Shell脚本的更多相关文章
- Java程序调用javascript等脚本的实现方法
public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodEx ...
- java连接ssh执行shell脚本
在liunx上写了一个shell脚本,想通过java去调用这个shell脚本,不知道怎么去调用,在网上说使用process这个进程方式,但是我执行机和我shell脚本都不在同一台电脑,老大说java中 ...
- Java程序调用带参数的shell脚本返回值
Java程序调用带参数的shell脚本返回值 首先来看看linux中shell变量(\(#,\)@,$0,$1,\(2)的含义解释 变量说明: - \)$ Shell本身的PID(ProcessI ...
- java 调用bash shell脚本阻塞的小问题的解决
java 调用bash shell脚本阻塞的小问题的解决 背景 使用java实现的web端,web端相应用户的界面操作,使用java调用bash实现的shell脚本进行实际的操作,操作完成返回执行结 ...
- rpyc + plumbum 实现远程调用执行shell脚本
rpyc可以很方便实现远程方法调用, 而plumbum则可以实现在python中类似shell的方式编码: 具体实现代码如下: Server.py import rpyc from rpyc.util ...
- [原]jenkins(六)---jenkins远程部署脚本
/** * lihaibo * 文章内容都是根据自己工作情况实践得出. * 版权声明:本博客欢迎转发,但请保留原作者信息! http://www.cnblogs.com/horizonli/p/533 ...
- linux c程序中获取shell脚本输出的实现方法
linux c程序中获取shell脚本输出的实现方法 1. 前言Unix界有一句名言:“一行shell脚本胜过万行C程序”,虽然这句话有些夸张,但不可否认的是,借助脚本确实能够极大的简化一些编程工作. ...
- 通过java程序调用ant build.xml配置文件中指定的target
一.概述 通过ant实现项目的自动化部署,jar包生成,替换,tomcat关停.启动,查看项目日志: 通过java程序调用已编辑好的ant脚本build.xml配置文件中指定的target: 文中文件 ...
- java classpath批量设置shell脚本
java classpath批量设置shell脚本 注意:linux bash jar文件之间的分隔符是':' export JAR_HOME=path to directory which ...
随机推荐
- Python大数据处理案例
分享 知识要点:lubridate包拆解时间 | POSIXlt利用决策树分类,利用随机森林预测利用对数进行fit,和exp函数还原 训练集来自Kaggle华盛顿自行车共享计划中的自行车租赁数据,分析 ...
- java基础38 正则表达式
1.常用的正则表达式 预定义字符类:. 任何字符(与行结束符可能匹配也可能不匹配) \d 数字:[0-9] \D 非数字: [^0-9] \s 空白字符:[ \t\n\x0B\f\r] \S ...
- LanguageTag
LanguageTag */--> div.org-src-container { font-size: 85%; font-family: monospace; } pre.src { bac ...
- Android Activity、Service、BroadcastReceiver 的生命周期
Activity.Service.BroadcastReceiver这三个组建是Android开发中最常使用到的组件,在它们的生命周期的各个阶段我们需要针对性的做些事情,了解这些组件的生命周期有利于我 ...
- 在Ubuntu 16.04 安装python3.6 环境并设置为默认
在Ubuntu 16.04 安装python3.6 环境并设置为默认 1.添加python3.6安装包,并且安装 sudo apt-get install software-properties-co ...
- 安装loadrunner11,卸载360浏览器后提示“无效的应用程序路径!请检查应用程序是否存在!”
我安装的loadrunner是11版本的,安装之前我的电脑上有安装了很多的浏览器,结果一开始录制脚本的时候,页面直接跳转到360浏览器上面了,但是显示正在录制的脚本为0个,于是就把360给卸载了,进行 ...
- Django实战(10):单元测试
尽早进行单元测试(UnitTest)是比较好的做法,极端的情况甚至强调“测试先行”.现在我们已经有了第一个model类和Form类,是时候开始写测试代码了. Django支持python的单元测试(u ...
- Bootstrap入门八:图片
1.响应式图片 在 Bootstrap 版本 3 中,通过为图片添加 .img-responsive 类可以让图片支持响应式布局.其实质是为图片设置了 max-width: 100%;. height ...
- 基于 Laravel 开发博客应用系列 —— 从测试开始(二):使用Gulp实现自动化测试
3.使用 Gulp 进行 TDD(测试驱动开发) Gulp 是一个使用 JavaScript 编写的自动化构建工具.用于对前端通用任务(如最小化.压缩.编译)进行自动构建.Gulp 还可以用来监控源代 ...
- Tensorflow入门(安装)
TensorFlow是将复杂的数据结构传输至人工智能神经网中进行分析和处理过程的系统.主要用于深度学习(神经网络)方面的研究与应用.Tensorflow适用与Python.C++.Java,本博客中主 ...