远程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>

原文地址:https://www.cnblogs.com/zhoufly-blog/p/10101077.html

时间: 2024-07-30 06:23:52

远程shell脚本执行工具类的相关文章

Java通过SSH2协议执行远程Shell脚本(ganymed-ssh2-build210.jar)

 该工具Jar包可在:http://download.csdn.net/detail/shenjianox/7769783及文档下载地址 ganymed-ssh2简介: Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包.在使用它的过程中非常容易,只需要指定合法的用户名口令, 或者授权认证文件,就可以创建到远程Linux主机的连接,在建立起来的会话中调用该Linux主机上的脚本文件,执行相关操作. 使用方法: 将 ganymed-ssh2-build210.

linux下shell脚本执行方法及exec和source命令

exec和source都属于bash内部命令(builtins commands),在bash下输入man exec或man source可以查看所有的内部命令信息. bash shell的命令分为两类:外部命令和内部命令.外部命令是通过系统调用或独立的程序实现的,如sed.awk等等.内部命令是由特殊的文件格式(.def)所实现,如cd.history.exec等等. 在说明exe和source的区别之前,先说明一下fork的概念. fork是linux的系统调用,用来创建子进程(child

shell脚本加密工具

1. 加密工具 1.1 gzexe 1.1.1 说明 gzexe是用来压缩执行文件的程序.当您去执行被压缩过的执行文件时,该文件会自动解压然后继续执行,和使用一般的执行文件相同. 1.1.2 安装 Linux自带,不用单独安装. 1.1.3 用法 gzexe filename.sh 它会把原来没有加密的文件备份为 file.sh~ ,同时 file.sh 即被变成加密文件. 1.1.4 参数 -d 解开压缩文件 1.2 shc 1.2.1 说明 shc是一个专业的加密shell脚本的工具,它的作

15 友盟项目--资源文件工具类(ResourceUtil)、sql执行工具类(ExecSQLUtil)

资源文件工具类把sql脚本转换为String字符串--->交给sql工具类ExecSQLUtil执行sql 1.资源文件工具类(ResourceUtil) 把sql脚本转换为String字符串 /** * 资源文件工具类 */ public class ResourceUtil { /** * 以String方式读取整个资源串 */ public static String readResourceAsString(String resource ,String charset) throws

&lt;zz&gt;linux运维自动化shell脚本小工具

from http://www.cnblogs.com/wang-li/p/5728461.html linux运维shell 脚本小工具,如要分享此文章,请注明文章出处,以下脚本仅供参考,若放置在服务器上出错,后果请自负 1.检测cpu剩余百分比 #!/bin/bash #Inspect CPU #Sun Jul 31 17:25:41 CST 2016 PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/hom

shell脚本执行及配置文件

linux之shell脚本执行及配置文件 bash脚本执行方法:     1 解释器直接运行         /usr/bin/bash bash FOO.sh     2 使用路径运行脚本(需要有x权限)         chmod +x FOO.sh         /PATH/TO/FOO.sh     3 使用.或source命令执行脚本         . /PATH/TO/FOO.sh         source /PATH/TO/FOO.sh     1,2执行方法和3执行方法的

shell脚本执行冲突事件-ssh&while

今天发现一个问题: 先看下脚本内容: [email protected]/0 # cat !$ cat /tmp/test_nginx ls *.txt | tr ' ' '\n' | while read line do  echo $line if [ 'yes' == 'yes' ] then ssh  192.168.109.10 "echo 'yes'" else ssh 192.168.109.10 "echo 'no'" fi done 上面脚本很简单

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

linux运维shell 脚本小工具,如要分享此文章,请注明文章出处,以下脚本仅供参考,若放置在服务器上出错,后果请自负 1.检测cpu剩余百分比 #!/bin/bash #Inspect CPU #Sun Jul 31 17:25:41 CST 2016 PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/wl/bin export PATH TERM=linux export TERM CpuResu

shell 脚本执行和基础知识

当我们给予shell脚本执行的权限后,就可以测试程序了,假设shell脚本文件为hello.sh放在/root目录下.下面介绍几种在终端执行shell脚本的方法:1.切换到shell脚本所在的目录,执行: [[email protected] home]# cd /root/[[email protected] ~]# ./hello.shhello guys!welcome to my Blog:linuxboy.org! 2.以绝对路径的方式执行: [[email protected] ~]