jsch的简单使用

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();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37208669/article/details/84815998