Java远程执行shell命令并拿到返回值

1 篇文章 0 订阅

所需jar包:

ganymed-ssh2-build210.jar

下载地址:

https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2/262

获取远程登录连接:

private static RemoteShellTool remoteShellTool = new RemoteShellTool("172.xxx.xxx.xxx", 62222, "root",
        "xxxxx", "utf-8");

RemoteShellTool相关代码如下:

package szsti.gasstation.utils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class RemoteShellTool {
    private Connection conn;
    private String ipAddr;
    private int port;
    private String charset = Charset.defaultCharset().toString();
    private String userName;
    private String password;

    public RemoteShellTool(String ipAddr, int port, String userName, String password,
                           String charset) {
        this.ipAddr = ipAddr;
        this.userName = userName;
        this.password = password;
        this.port = port;
        if (charset != null) {
            this.charset = charset;
        }
    }

    public boolean login() throws IOException {
        conn = new Connection(ipAddr, port);
        conn.connect(); // 连接
        boolean res_con=conn.authenticateWithPassword(userName, password);
        return res_con; // 认证
    }

    public void close() throws IOException {
        conn.close(); // 断开连接
    }

    /**
     *
     * @param cmds
     * @param isOpen  为null时是查询pid,关闭进程命令,执行完命令去读结果,不为空时是开启,执行完命令直接关闭
     * @return
     */
    public String exec(String cmds, String isOpen) {
        InputStream in = null;
        String result = "";
        try {
            if (this.login()) {
                Session session = conn.openSession(); // 打开一个会话
                session.requestPTY("bash");
                session.execCommand(cmds);
                in = session.getStdout();
                if (StringUtils.isBlank(isOpen)) {
                    result = this.processStdout(in, this.charset);
                }else{
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                session.close();
                conn.close();


            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return result;
    }

    public String processStdout(InputStream in, String charset) {

        byte[] buf = new byte[1024];
        StringBuffer sb = new StringBuffer();
        try {
            while (in.read(buf) != -1) {
                sb.append(new String(buf, charset));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


}

根据传入的进程名通过cmds命令,远程执行,获取相应的返回值:

public static List<String> getPidLinuxCmd(String processName) {
    String cmd = "ps -ef|grep " + processName + " | grep -v grep";
    String result = remoteShellTool.exec(cmd, null);
    String[] arrs = result.split("\n");
    List<String> pids = new ArrayList<>();
    for (int i = 0; i < arrs.length - 1; i++) {
        String thatPid = arrs[i].split("\\s+")[1];
        if ("-f".equals(thatPid)) {
            break;
        }
        pids.add(thatPid);
    }
    return pids;
}

以上示例为根据进程名,获取相应的pid序列号.

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值