JAVA通过ssh连接远程机器执行shell命令

添加依赖

  • 添加依赖
  • 代码示例

添加依赖

<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>262</version>
</dependency>

代码示例

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class ExecuteCommand {

    private static final String HOST_NAME = "要连接主机的ip地址";
    private static final String USER = "要连接主机用户名";
    private static final String PASSWORD = "要连接主机用户密码";
    private static Connection conn;

    public static final String CMD_CREATE_REPO = "pachctl create repo";
    public static final String CMD_DELETE_REPO = "pachctl delete repo";
    private static Boolean login() {
        boolean flag = false;
        try {
            conn = new Connection(HOST_NAME);
            conn.connect();
            flag = conn.authenticateWithPassword(USER, PASSWORD);
        } catch (IOException ex) {
            log.error("连接 pachyterm 主机异常", ex);
        }
        return flag;
    }

    public static boolean execute(String cmd) {
        boolean result = login();
        try {
            if (result) { //登录成功
                System.out.println("登录成功:");
                log.info("登录成功:");
                Session session = conn.openSession();
                session.requestPTY("bash");
                session.startShell();
                PrintWriter out = new PrintWriter(session.getStdin());
                out.println(cmd);
                out.flush();
                out.println("exit");
                out.close();
                session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,
                        30000);
                System.out.println("exec finished!");
                session.close();
                conn.close();
            }
        } catch (Exception ex) {
            log.error("执行命令异常", ex);
            result = false;
        }
        return result;
    }
}

你可能感兴趣的:(java,java,ssh,服务器)