/**
* 远程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脚本执行工具类的更多相关文章

  1. 【原】Java程序调用远程Shell脚本

    此程序的目的是执行远程机器上的Shell脚本. [环境参数]远程机器IP:192.168.234.123用户名:root密码:rootShell脚本的路径:/home/IFileGenTool/Bak ...

  2. windows下建立文件的换行符^M导致linux下的shell脚本执行错误的解决方式

    常常在windows下编辑的文件远程传送到linux下的时候每行末尾都会出现^M.这将导致shell脚本执行错误,主要是由于dos下的编辑器和linux下的编辑器对文件末行的回车符处理不一致导致. 主 ...

  3. 用java代码调用shell脚本执行sqoop将hive表中数据导出到mysql

    1:创建shell脚本 touch sqoop_options.sh chmod 777 sqoop_options.sh 编辑文件  特地将执行map的个数设置为变量  测试 可以java代码传参数 ...

  4. Linux之Shell 脚本加密工具-shc

    Much effort, much prosperity. 为什么要加密Shell脚本呢?当然是为了安全! 可能脚本里面涉及到密码之类的就需要进行加密了 一.下载安装shc工具 要保护自己编写的she ...

  5. linux运维自动化shell脚本小工具

    linux运维shell 脚本小工具,如要分享此文章,请注明文章出处,以下脚本仅供参考,若放置在服务器上出错,后果请自负 1.检测cpu剩余百分比 #!/bin/bash #Inspect CPU # ...

  6. shell脚本执行错误 $'\r':command not found

    shell脚本执行错误 $'\r':command not found Linux下有命令dos2unix 可以用一下命令测试 vi -b filename 我们只要输入dos2unix *.sh就可 ...

  7. 2.8 补充:shell脚本执行方法

    bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限.   方法一:切换到shell脚本 ...

  8. linux下shell脚本执行jar文件

    最近在搞一个shell脚本启动jar文件个关闭jar文件的东东.搞得我都蛋疼了.今天晚上终于弄好了 话说,小弟的linux只是刚入门,经过各方查资料终于搞定了.话不多说,下面开始上小弟写的shell脚 ...

  9. shell脚本 awk工具

    awk工具概述awk编程语言/数据处理引擎基于模式匹配检查输入文本,逐行处理并输出通常在shell脚本中,或取指定的数据单独用时,可对文本数据做统计 命令格式格式一:awk [选项] '[条件]{编辑 ...

随机推荐

  1. L2-006 树的遍历 (25 分)

    链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805069361299456 题目: 给定一棵二叉树的后序遍历和中序 ...

  2. Agiliq署名的免费python书籍

    在他们的官网介绍中,说他们团队自2009年开始使用Django,Python,Postgres,Augular等工具来开发webapp,移动应用后台等.并且,他们还有一个Github组织,开源了相当多 ...

  3. Nginx配置SSL证书部署HTTPS方法

    1.申请域名,绑定服务器ip(我申请的是阿里云服务器,以下就此为例) 2.可以在阿里云上免费申请SSL证书(下载证书,后续会用到) 3.在服务器中配置证书 在服务器上安装Nginx 将下载好的证书上传 ...

  4. vue打包遇到的坑

    1.-webkie-box-orient:vertical没大打包上,解决方案 /* ! autoprefixer: off */ -webkit-box-orient: vertical; /* a ...

  5. 如何配置adb环境变量

    如何配置adb环境变量? 1.我的电脑---控制面板---高级系统设置 2.点击[高级系统设置],弹出系统属性的弹框, 3.点击[环境变量],弹出环境变量弹框,新建一个系统变量,命名为Android ...

  6. tomcat启动后产生的日志

    产生的日志  相当于 定时选取webapps里面搜索有没有超时的session,然后将超时的session关掉. 每一个webapp 都是独立的 一个application对应一个context,se ...

  7. 2141:2333(zznuoj)

    2141: 2333 时间限制: 1 Sec  内存限制: 128 MB提交: 77  解决: 17[提交] [状态] [讨论版] [命题人:admin] 题目描述 “别人总说我瓜,其实我一点也不瓜, ...

  8. Jenkins编辑或替换All view

    为什么我不能编辑“All”view? 这是因为它的类型是“All”而不是“List”,并且“All”类型是不可编辑的.你只能有一个“All”类型的view. 如果你想编辑这个View,你将不得不创建一 ...

  9. ef core自动映射

    原回答:https://stackoverflow.com/questions/26957519/ef-core-mapping-entitytypeconfiguration 一.反射 protec ...

  10. 想明白为什么C->D

    C公司为什么不行? 钱不够 第一个原因是在新世界,C能够给我的钱是远远低于市场价的.如果按照现公司的行情,也就一个社招人员的白菜价. 领导不行 C公司的领导,从面相上看就无法让我信服.领导力中下,忽悠 ...