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

使用下面这个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);
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容