/**
* 远程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. 安装YApi 接口管理平台

    yum install mongodb yum install -y nodejs git clone https://gitee.com/mirrors/YApi.git 克隆项目到本地 使用命令进 ...

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

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

  3. [HASH]MOD运算用户哈希函数

    一.概述 MOD(取模)运算配合质数的特性,可以实现一种简单的哈希算法. 二.基于的定理 在理解如何实现mod哈希前应当了解一些数学的定理: 1.x mod y = z ,实际上是x除以y的余数y的意 ...

  4. vue轮播图中间大两头小

    <template> <div v-if="items.length" class="full-page-slide-wrapper"> ...

  5. 微服务杂谈--EureKa及自我保护

    时值初夏,各位老官的心也有所悸动,这不,众看官搬好小板凳,沏一壶清茶,待听Jerry话谈Eureka,以此静心.话不多少,且听: 一.微服务的产生 单体应用:一个jar或者一个war包交给运维,运行在 ...

  6. VS Code 1.28版本设置中文界面的方法

    最近将vscode升级到1.28版本,发现升级后默认界面变成英文了,而且在按照网上的说法在locale.json设置locale: "zh-cn"也不起效,解决的解决方法很简单: ...

  7. leetcode python两数之和返回索引

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 15], target ...

  8. RabbitMQ通过Exchange.headers属性代替routekey,x-match实现队列精准匹配

    消费者: static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory() { HostNam ...

  9. Python2.7和3.7区别

    区别一:print语法使用 Python2.7   print语法使用   >>> print "Hello Python" Python3.7   print语 ...

  10. 如何从Eclipse导入github上的项目源码--转载

    [转载出处声明:hil2000的专栏] 1.首先在github.com上申请一个账号,比如笔者的账号为puma0072.Eclipse需要安装egit插件,在Eclipse中选择help->Ma ...