jsch的简单使用

本文介绍如何使用JSch库在Java中实现SSH协议,进行远程文件操作,包括连接服务器、列出目录文件等。通过具体代码示例,展示了如何处理SSH-2.0-OpenSSH_5.3协议不被支持的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Could not parse response code.Server Reply: SSH-2.0-OpenSSH_5.3
服务器不支持协议,使用JSch

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.54</version>
        </dependency>
package com.xxl.job.executor;

import com.jcraft.jsch.*;

import java.io.IOException;
import java.util.Properties;
import java.util.Vector;

/**
 * Created by nbcoolkid on 2017-12-27.
 */
public class Main {
    public static void main(String[] args) throws IOException {
//        FTPClient ftpClient = new FTPClient();
//        ftpClient.connect("vm.docker",22);
//        boolean b = ftpClient.login("docker","docker");
//        System.out.println("连接成功:"+b);
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;

        String username = "docker";
        String host = "vm.docker";
        String password = "docker";
        int port = 22;

        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            System.out.println("连接成功");
            channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            Vector vector = sftp.ls("/home/docker/opt/pcre-8.40");
            for (Object item:vector) {
                ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) item;
                System.out.println(entry.getFilename());
            }

        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        }finally {
            closeChannel(sftp);
            closeChannel(channel);
            closeSession(sshSession);
        }

    }

    private static void closeChannel(Channel channel) {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
    }

    private static void closeSession(Session session) {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值