Java远程连接Linux服务器执行shell指令

一、应用场景
我们的Java服务和Pulsar消息中间件不是部署在同一台机器,而我们需要创建token用于pulsar认证,但是Pulsar的Java客户端代码并不提供现成的方法,于是需要用Java远程连接Linux,再执行命令创建token

二、代码
0.pom依赖

        <dependency><groupId>ch.ethz.ganymedgroupId><artifactId>ganymed-ssh2artifactId><version>262version>dependency>

1.工具类代码

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;import java.io.*;
import java.util.Locale;public class ExecUtil {// 登录, host 远程主机IP, username 用户名 password 密码 端口默认为22private static Connection login(String host, String username, String password) throws IOException {Connection conn = new Connection(host);conn.connect();if (!conn.authenticateWithPassword(username, password)) {throw new RuntimeException("用户名或密码错误!");}return conn;}// 执行远程linux命令行public static String remoteExec(String cmd, String host, String username, String password) throws IOException {//登录,获取连接Connection conn = login(host, username, password);Session session = null;BufferedReader br = null;InputStream is = null;StringBuffer res = new StringBuffer();try {// 开启会话session = conn.openSession();// 执行命令session.execCommand(cmd, "UTF-8");// 处理输出内容is = new StreamGobbler(session.getStdout());br = new BufferedReader(new InputStreamReader(is));String line;while ((line = br.readLine()) != null) {res.append(line);}} finally {//关闭资源try {if (is != null) {is.close();}if (br != null) {br.close();}if (session != null) {session.close();}if (conn != null) {conn.close();}} catch (Exception e) {e.printStackTrace();}}return res.toString();}/*** 执行本机linux命令行,与ganymed-ssh2依赖无关,JDK自带功能*/public static String exec(String command) {String osName = System.getProperty("os.name");try {/*系统命令不支持的操作系统Windows XP, 2000 2003 7 8 9 10 11*/if (osName.toLowerCase(Locale.ROOT).indexOf("win") != -1) {throw new RuntimeException("不支持的操作系统:" + osName);}Runtime rt = Runtime.getRuntime();Process process = rt.exec(command);LineNumberReader br = new LineNumberReader(new InputStreamReader(process.getInputStream()));StringBuffer sb = new StringBuffer();String line;while ((line = br.readLine()) != null) {sb.append(line).append("\n");}return sb.toString();} catch (Exception e) {throw new RuntimeException(e);}}
}

2.测试

public class TestExecUtil {@Testpublic void test1() throws IOException {String s = ExecUtil.remoteExec("mkdir /home/bili", "192.xxx.xxx.xxx", "root", "bikabika");System.out.println(s);}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部