Java实现Apache sshd客户端(密码和公钥登录并执行命令)

本文介绍如何利用Apache Sshd库在Java中实现SSH连接,并远程执行命令。通过示例代码展示了如何设置SSH客户端,使用密码或公钥进行身份验证,以及执行远程命令并获取结果。

第一步:引入依赖

<dependency>
        <groupId>org.apache.sshd</groupId>
        <artifactId>sshd-core</artifactId>
        <version>2.1.0</version>
</dependency>

第二步:准备执行代码 

import lombok.Getter;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.util.security.SecurityUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

public class SshdExecutor {

    SshClient client;
    ClientSession session;

    @Getter
    private String result;
    @Getter
    private String error;

    public SshdExecutor(String ip, Integer port, String user) {
        client = SshClient.setUpDefaultClient();
        client.start();
        try {
            session = client.connect(user, ip, port).verify(10 * 1000).getSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //密码方式
    public SshdExecutor(String ip, Integer port, String user, String password) {
        this(ip, port, user);
        session.addPasswordIdentity(password);
    }

    //公钥方式
    public SshdExecutor(String ip, Integer port, String user, String keyName, String publicKey) {
        this(ip, port, user);
        try {
            session.addPublicKeyIdentity(SecurityUtils.loadKeyPairIdentity(keyName, new ByteArrayInputStream(publicKey.getBytes()), null));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
    }
    
    //执行命令
    public void execute(String command) {
        try {
            if (!session.auth().verify(10 * 1000).isSuccess()) {
                throw new Exception("auth faild");
            }

            ClientChannel channel = session.createExecChannel(command);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayOutputStream err = new ByteArrayOutputStream();
            channel.setOut(out);
            channel.setErr(err);

            if (!channel.open().verify(10 * 1000).isOpened()) {
                throw new Exception("open faild");
            }
            List<ClientChannelEvent> list = new ArrayList<>();
            list.add(ClientChannelEvent.CLOSED);
            channel.waitFor(list, 10 * 1000);
            channel.close();
            result = out.toString();
            error = err.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                try {
                    client.stop();
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

参考文章:https://www.cnblogs.com/sybblogs/p/11555279.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值