远程shell脚本执行工具类
/**
* 远程shell脚本执行工具类
*/
public class RemoteShellExecutorUtils {
private static final Logger logger = LoggerFactory.getLogger(RemoteShellExecutorUtils.class); private Connection conn;
/**
* 服务器IP
*/
private String ip;
/**
* 用户名
*/
private String user;
/**
* 密码
*/
private String password;
private String charset = Charset.defaultCharset().toString(); private static final int TIME_OUT = 1000 * 5 * 60; /**
* 构造函数
*
* @param ip 服务器地址
* @param user 用户名
* @param pwd 密码
*/
public RemoteShellExecutorUtils(String ip, String user, String pwd) {
this.ip = ip;
this.user = user;
this.password = pwd;
} /**
* 登录
*
* @return
* @throws IOException
*/
private boolean login() throws IOException {
conn = new Connection(ip);
conn.connect();
return conn.authenticateWithPassword(user, password);
} /**
* 执行脚本
*
* @param cmd shell命令
* @return
*/
public Map<String,String> exec(String cmd) {
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
Map<String,String> map = new HashMap<String,String>();
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(cmd); stdOut = new StreamGobbler(session.getStdout());
outStr = processStream(stdOut, charset);
map.put("outStr",outStr); stdErr = new StreamGobbler(session.getStderr());
outErr = processStream(stdErr, charset);
map.put("outErr",outErr); session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT); System.out.println("outStr=" + outStr);
System.out.println("outErr=" + outErr); ret = session.getExitStatus();
map.put("ret",ret+"");
} else {
logger.error("登录远程机器失败:" + ip);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
if (stdOut != null) {
stdOut.close();
}
if (stdErr != null) {
stdErr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
} /**
* @param in 输入流
* @param charset 字符编码
* @return
* @throws Exception
*/
private String processStream(InputStream in, String charset) throws IOException {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
return sb.toString();
} /**
* 关闭连接
*/
public void close(){
if(conn != null){
conn.close();
}
} public static void main(String[] args) {
RemoteShellExecutorUtils executorUtils = new RemoteShellExecutorUtils("172.22.2.118",
"hadoop", "hadoop");
String shell = String.format("sh %s %s %s %s", "/dataexchange/kafka/create.sh",
"topic_create_test", "1", "2"); // String shell = String.format("sh %s %s", "/dataexchange/kafka/topics.sh","topic_create_test"); Map<String,String> map = executorUtils.exec(shell); if("".equals(map.get("outStr")) && "".equals(map.get("outErr")) && "0".equals(map.get("ret"))){
System.out.println("topic不存在");
} else if (!"".equals(map.get("outErr"))){
System.out.println("远程shell脚本执行异常>>>>"+map.get("outErr"));
} else if (!"".equals(map.get("outStr"))){
System.out.println("topic已存在");
}
}
} 依赖包
<dependency>
<groupId>org.jvnet.hudson</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210-hudson-1</version>
</dependency>
远程shell脚本执行工具类的更多相关文章
- 【原】Java程序调用远程Shell脚本
此程序的目的是执行远程机器上的Shell脚本. [环境参数]远程机器IP:192.168.234.123用户名:root密码:rootShell脚本的路径:/home/IFileGenTool/Bak ...
- windows下建立文件的换行符^M导致linux下的shell脚本执行错误的解决方式
常常在windows下编辑的文件远程传送到linux下的时候每行末尾都会出现^M.这将导致shell脚本执行错误,主要是由于dos下的编辑器和linux下的编辑器对文件末行的回车符处理不一致导致. 主 ...
- 用java代码调用shell脚本执行sqoop将hive表中数据导出到mysql
1:创建shell脚本 touch sqoop_options.sh chmod 777 sqoop_options.sh 编辑文件 特地将执行map的个数设置为变量 测试 可以java代码传参数 ...
- Linux之Shell 脚本加密工具-shc
Much effort, much prosperity. 为什么要加密Shell脚本呢?当然是为了安全! 可能脚本里面涉及到密码之类的就需要进行加密了 一.下载安装shc工具 要保护自己编写的she ...
- linux运维自动化shell脚本小工具
linux运维shell 脚本小工具,如要分享此文章,请注明文章出处,以下脚本仅供参考,若放置在服务器上出错,后果请自负 1.检测cpu剩余百分比 #!/bin/bash #Inspect CPU # ...
- shell脚本执行错误 $'\r':command not found
shell脚本执行错误 $'\r':command not found Linux下有命令dos2unix 可以用一下命令测试 vi -b filename 我们只要输入dos2unix *.sh就可 ...
- 2.8 补充:shell脚本执行方法
bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本 ...
- linux下shell脚本执行jar文件
最近在搞一个shell脚本启动jar文件个关闭jar文件的东东.搞得我都蛋疼了.今天晚上终于弄好了 话说,小弟的linux只是刚入门,经过各方查资料终于搞定了.话不多说,下面开始上小弟写的shell脚 ...
- shell脚本 awk工具
awk工具概述awk编程语言/数据处理引擎基于模式匹配检查输入文本,逐行处理并输出通常在shell脚本中,或取指定的数据单独用时,可对文本数据做统计 命令格式格式一:awk [选项] '[条件]{编辑 ...
随机推荐
- 简单python接口测试编写和django开发环境的搭建
安装django环境 启动django D:\python\imooc>python manage.py runserver 0.0.0.0:8000 命令行下django新建app D:\py ...
- windows 下 配置 github
github 功能介绍 1. 记录多个版本 2.查看历史操作,可以进行版本回退和前进的控制 3. 多端共享代码,自动合成 Github 与 SVN 1. SVN 版本集中管理,所 ...
- 详解PROTOCOL BUFFERS
1. 前言 Protocal Buffers是google推出的一种序列化协议.由于它的编码和解码的速度,已经编码后的大小控制的较好,因此它常常被用在RPC调用中,传递参数和结果.比如gRPC. Pr ...
- bat实现固定时间循环抓取设备log
背景:测试时需要实时抓取android设备log,但是一份log抓取过来非常庞大(有时超过500M+,编辑器都打不开,还得找工具进行分割,甚是蛋疼),查看也非常不方便. 解决:基于上述情况,与其之后进 ...
- canal-随记001-吐血一个下午找bug
前天leader说,阿里的新版本canal支持 canal收集binlog直接发到kafka,你要不研究一下? ok,没问题. 昨天周六,在家搭了套环境.解决centos7安装mysql各种小细节,按 ...
- BLO(bzoj1123)
Description Byteotia城市有n个 towns, m条双向roads. 每条 road 连接 两个不同的 towns ,没有重复的road. 所有towns连通. Input 输入n和 ...
- 【pG&&CYH-01】元旦联欢会
题解: t1: 题解是循环矩阵 但我并没有往矩阵上想下去... 这个东西比较显然的是可以把它看成生成函数 然后就可以任意模数fft了 复杂度比题解优 $nlog^2$ t2: 随便推推式子就好了 t3 ...
- 数据分析入门——numpy类库基础知识
numpy类库是数据分析的利器,用于高性能的科学计算和数据分析.使用python进行数据分析,numpy这个类库是必须掌握的.numpy并没有提供强大的数据分析功能,而是它提供的ndarray数据结构 ...
- SourceInSight自定义命令说明与应用
1.自定义命名设置界面(Tool -> Custom Commands...) Command 显示当前选中命令的名字. 下拉列表中包含了所有的自定义命令. Run 命令行,当调用自定义命令时, ...
- docker 安装mysql
1.安装docker 参见这个文章第一步:https://www.cnblogs.com/yanglei-xyz/p/10600707.html 2.安装mysql 查找Docker Hub上的mys ...