远程连接linux或者本地执行shell

远程连接linux或者本地执行shell,单例模式


import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.alibaba.druid.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * @ClassName: RemoteConnection
 * @Description: TODO
 * @Author Tan
 * @Date 2019/7/27
 */
public class RemoteConnection {

    private final static Logger log = LoggerFactory.getLogger(RemoteConnection.class);

    private static RemoteConnection instance;

    private static String DEFAULTCHART = "UTF-8";

    private static Connection conn = null;

    private static String SERVER = "linux";
    private static String IP = "192.168.1.2";
    private static String HOST_NAME = "root";
    private static String HOST_PWD = "123456";

    public static synchronized RemoteConnection getInstance() {
        if (instance == null) {
            instance = new RemoteConnection();
        }
        return instance;
    }

    public static synchronized Connection getCon(String ip, String userName, String userPwd) {
        if (conn == null) {
            conn = login(ip, userName, userPwd);
        }
        return conn;
    }

    /**
     * 登录主机
     *
     * @return 登录成功返回true,否则返回false
     */
    public static Connection login(String ip, String userName, String userPwd) {
        boolean flg = false;
        Connection conn = null;
        try {
            conn = new Connection(ip);
            conn.connect();
            flg = conn.authenticateWithPassword(userName, userPwd);//认证
            if (flg) {
                log.debug("登录成功" + conn);
                return conn;
            }
        } catch (IOException e) {
            log.debug("登录失败" + e.getMessage());
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 远程执行shll脚本或者命令  使用默认的cmd文件
     *
     * @param cmd 即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    public static String execute(String cmd, String ip, String host, String pwd) {
        String result = "";
        Connection conn = getCon(ip, host, pwd);
        try {
            if (conn != null) {
                Session session = conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                //如果为得到标准输出为空,说明脚本执行出错了
                if (StringUtils.isEmpty(result)) {
                    log.debug("得到标准输出为空, 链接conn:" + conn + ",执行的命令:" + cmd);
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                } else {
                    log.debug("执行命令成功, 链接conn:" + conn + ",执行的命令:" + cmd);
                }
                session.close();
            }
        } catch (IOException e) {
            log.debug("执行命令失败,链接conn:" + conn + ",执行的命令:" + cmd + "  " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     *
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     */
    private static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
        } catch (UnsupportedEncodingException e) {
            log.error("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 执行本地linux命令
     * 部署到linuxs时不需要登录,直接调此方法执行
     * @param cmd
     * @return
     */
    public static String execCommand(String cmd) {
        String result = "";
        String[] cmds = new String[]{"sh", "-c", cmd};
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmds);
            result = processStdout(proc.getInputStream(), DEFAULTCHART);
            //如果为得到标准输出为空,说明脚本执行出错了
            if (StringUtils.isEmpty(result)) {
                log.debug("执行的命令无结果:" + cmd);

            } else {
                log.debug("执行命令成功, 执行的命令:" + cmd);
            }

        } catch (Exception e) {
            log.debug("执行命令失败,执行的命令:" + cmd + "  " + e.getMessage());
            e.printStackTrace();
        }

        return result;

    }

    public static void main(String[] args) {

        
        String cmd = "ps  aux | grep tomcat | grep -v grep";
        String execute = null;
        if ("Linux".equalsIgnoreCase(SERVER)) {
            execute = RemoteConnection.getInstance().execCommand(cmd); //linux
        } else {
            execute = RemoteConnection.getInstance().execute(cmd, IP, HOST_NAME, HOST_PWD);//Windows远程调用执行
        }

        log.info(execute);
        
    }

}

其中有个坑

就是执行复杂命令时如:ps -ef|grep tomcat  时

 Process proc = rt.exec(cmd); 执行无结果返回

必须将命令转成数组形式

String[] cmds = new String[]{"sh", "-c", cmd};
Process proc = rt.exec(cmds);


 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cy谭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值