Java 连接ssh工具总结

1. JSch

![Alt](https://img-home.csdnimg.cn/images/20220524100510.png

maven仓库

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

百度Java使用ssh工具这个提到的最多,具体方法调用等可百度,有很多参考,可自行搜索。
由于个人都没跑通,所以这里就不放了。

2. Apache sshd

apache sshd github 地址:https://github.com/apache/mina-sshd/tree/master

maven仓库

<dependency>
            <groupId>org.apache.sshd</groupId>
            <artifactId>sshd-core</artifactId>
            <version>2.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.sshd</groupId>
            <artifactId>sshd-sftp</artifactId>
            <version>2.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.sshd</groupId>
            <artifactId>sshd-scp</artifactId>
            <version>2.9.3</version>
        </dependency>
        // 这个是解决报sddsa错误的问题
        <dependency>
            <groupId>net.i2p.crypto</groupId>
            <artifactId>eddsa</artifactId>
            <version>0.3.0</version>
        </dependency>

基本使用

package com.xteamsoft.refactor.web.util;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelExec;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.scp.client.ScpClient;
import org.apache.sshd.scp.client.SimpleScpClient;
import org.apache.sshd.scp.client.SimpleScpClientImpl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;

public class SshClientExample {

    public static void main(String[] args) {
        String host = "your host";
        String username = "your username";
        String password = "your password";
        int port = your port;
        String localPath = "path"; // 本地地址
        String remotePath = "path"; // 服务器地址
        try {
//            upload(host,username,password,localPath,remotePath);
//            download(host,username,password,localPath,remotePath);
            execute(host,port,username,password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 上传
     * @param host 主机ip
     * @param username 用户名
     * @param password 密码
     * @param localPath 本地目录
     * @param remotePath 远程目录
     */
    public static void upload(String host, String username, String password, String localPath, String remotePath) throws IOException{
        SshClient client = SshClient.setUpDefaultClient();
        try(SimpleScpClient scpClient = new SimpleScpClientImpl(SshClient.wrapAsSimpleClient(client))) {
            // Open the client
            client.start();
            ScpClient scp = scpClient.scpLogin(host, username, password);
            // ScpClient.Option.Recursive : 当 localPath 为目录,且目录中有多层子目录和文件时,该选项会将目录下的所有文件递归的上传至远程目录中。
            // ScpClient.Option.TargetIsDirectory :该选项,说明 ScpClient.upload 方法的 remote 参数为远端的目录,而不是文件。
            scp.upload(localPath, remotePath , ScpClient.Option.Recursive, ScpClient.Option.TargetIsDirectory);
        } finally {
            client.stop();
        }
    }

    /**
     * 下载
     * @param host 主机ip
     * @param username 用户名
     * @param password 密码
     * @param localPath 本地目录
     * @param remotePath 远程目录
     */
    public static void download(String host, String username, String password, String localPath, String remotePath)throws IOException{
        SshClient client = SshClient.setUpDefaultClient();
        try(SimpleScpClient scpClient = new SimpleScpClientImpl(SshClient.wrapAsSimpleClient(client))) {
            // Open the client
            client.start();
            ScpClient scp = scpClient.scpLogin(host, username, password);
            // ScpClient.Option.Recursive : 当 localPath 为目录,且目录中有多层子目录和文件时,该选项会将目录下的所有文件递归的上传至远程目录中。
            // ScpClient.Option.TargetIsDirectory :该选项,说明 ScpClient.upload 方法的 remote 参数为远端的目录,而不是文件。
            scp.download(remotePath, localPath , ScpClient.Option.Recursive, ScpClient.Option.TargetIsDirectory);
        } finally {
            client.stop();
        }
    }



    public static void execute(String host, int port, String username, String password) {
        String cmd = "whoami";
        SshClient client = SshClient.setUpDefaultClient();
        ClientSession session = null;
        try {
            client.start();
            ConnectFuture connectFuture = client.connect(username, host, port).verify(10, TimeUnit.SECONDS);
            if (connectFuture.isConnected()) {
                session = connectFuture.getSession();
                session.addPasswordIdentity(password);
                AuthFuture auth = session.auth().verify(10, TimeUnit.SECONDS);
                if (auth.isSuccess()) {
                    channelCmd(session, cmd);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (session != null) {
                    session.close();
                }
                client.close();
            } catch (IOException e) {
                System.out.println("关闭异常");
            }
        }
    }

    private static void channelCmd(ClientSession session, String cmd) throws IOException {
        ChannelExec channel = session.createExecChannel(cmd);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ByteArrayOutputStream outputErr = new ByteArrayOutputStream();
        channel.setOut(output);
        channel.setErr(outputErr);
        channel.open();
        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
        System.out.println(output);
        System.out.println(outputErr);
    }

}

参考文章地址:

SshClient客户端 连接服务器执行命令: https://blog.csdn.net/antony1776/article/details/116894124
使用 Apache sshd scp 上传或下载文件: https://blog.csdn.net/weixin_43859729/article/details/133929263

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值