美文网首页
devops-java远程调用ssh2执行Linux命令

devops-java远程调用ssh2执行Linux命令

作者: JavaHub | 来源:发表于2020-06-23 17:12 被阅读0次

使用下面这个Java包
maven

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

ssh 两种方式:1.用户名密码。2.做面密配置,

api使用方式

//name password
private Connection getConnectionWithPassword() {
        conn = new Connection(host, sshPort);
        try {
            conn.connect();
            boolean auth = conn.authenticateWithPassword(userName, password);
            if (auth) {
                logger.debug("{},主机认证成功", resourcesEntity.getHost());
                return conn;
            } else {
                throw new DefaultBusiException("ssh连接失败,请检查用户名、密码、ssh端口");
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new DefaultBusiException("ssh连接失败,请检查用户名、密码、ssh端口");
        }
    }

//publickey
private Connection getConnectionWithPublicKey() {
        conn = new Connection(host, sshPort);
        try {
            conn.connect();
            boolean auth = conn.authenticateWithPublicKey(userName, new File(sshPrivateKeyPath), sshPassword());
            if (auth) {
                logger.debug("{},主机认证成功", resourcesEntity.getHost());
                return conn;
            } else {
                throw new DefaultBusiException("ssh连接失败,请检查用户名、密码、ssh端口");
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new DefaultBusiException(e);
        }
    }

相关文章

网友评论

      本文标题:devops-java远程调用ssh2执行Linux命令

      本文链接:https://www.haomeiwen.com/subject/krlevhtx.html