java - 如何使用 JSch 访问 FTP 服务器?

标签 java ftp sftp jsch

我在本地 Windows 7 机器上安装了 FileZilla FTP Server。 我还在同一台机器上安装了 FileZilla FTP 客户端。 两者之间的连接成功确认服务器和客户端伙伴关系存在。

我编写了一个用于连接到 FileZilla FTP 服务器的快速而肮脏的小 Jsch 程序,下面是该程序:

public class TestJSch {

/** Creates a new instance of TestCommonsNet */
public TestJSch() {
}

/**
 * main - Unit test program
 * 
 * @param args
 *            Command line arguments
 * 
 */
public static void main(String[] args) {
    try {
        String ftpHost = "127.0.0.1";
        int ftpPort = 21;// 14147;
        // int ftpPort = 990;// 14147;
        String ftpUserName = "kedar";
        String ftpPassword = "XXXXXXXXXXX";
        String ftpRemoteDirectory = "C:\\KEDAR\\Java\\FTP_Folder";
        String fileToTransmit = "C:\\KEDAR\\Java\\File_Folder\\Customer.txt";
        String identityfile = "C:\\KEDAR\\Java\\Ftp\\certificate.crt";

        //
        // First Create a JSch session
        //
        JSch.setLogger(new MyLogger());
        System.out.println("Creating session.");

        JSch jsch = new JSch();

        String knownHostsFilename = "C:\\Windows\\System32\\drivers\\etc\\hosts";
        jsch.setKnownHosts(knownHostsFilename);
        jsch.addIdentity(identityfile);
        Session session = null;
        Channel channel = null;
        ChannelSftp c = null;

        //
        // Now connect and SFTP to the SFTP Server
        //
        try {
            // Create a session sending through our username and password
            session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
            System.out.println("Session created.");
            session.setPassword(ftpPassword);
            // Security.addProvider(new com.sun.crypto.provider.SunJCE());

            // b
            // Setup Strict HostKeyChecking to no so we dont get the
            // unknown host key exception
            //
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            System.out.println("Session connected.");

            //
            // Open the SFTP channel
            //
            System.out.println("Opening Channel.");
            channel = session.openChannel("sftp");
            channel.connect();
            c = (ChannelSftp) channel;
        } catch (Exception e) {
            System.err.println("Unable to connect to FTP server."
                    + e.toString());
            throw e;
        }

        //
        // Change to the remote directory
        //
        System.out.println("Changing to FTP remote dir: "
                + ftpRemoteDirectory);
        c.cd(ftpRemoteDirectory);

        //
        // Send the file we generated
        //
        try {
            File f = new File(fileToTransmit);
            System.out.println("Storing file as remote filename: "
                    + f.getName());
            c.put(new FileInputStream(f), f.getName());
        } catch (Exception e) {
            System.err
                    .println("Storing remote file failed." + e.toString());
            throw e;
        }   

        //
        // Disconnect from the FTP server
        //
        try {
            c.quit();
        } catch (Exception exc) {
            System.err.println("Unable to disconnect from FTPserver. "
                    + exc.toString());
        }

    } catch (Exception e) {
        System.err.println("Error: " + e.toString());
    }

    System.out.println("Process Complete.");
    System.exit(0);
}

public static class MyLogger implements com.jcraft.jsch.Logger {
    static java.util.Hashtable name = new java.util.Hashtable();
    static {
        name.put(new Integer(DEBUG), "DEBUG: ");
        name.put(new Integer(INFO), "INFO: ");
        name.put(new Integer(WARN), "WARN: ");
        name.put(new Integer(ERROR), "ERROR: ");
        name.put(new Integer(FATAL), "FATAL: ");
    }

    public boolean isEnabled(int level) {
        return true;
    }

    public void log(int level, String message) {
        System.err.print(name.get(new Integer(level)));
        System.err.println(message);
    }
}
}

我尝试运行这个程序,下面是 FTP 日志:

(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> Connected, sending welcome message...
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> 220-FileZilla Server version 0.9.39 beta
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> 220-written by Tim Kosse (Tim.Kosse@gmx.de)
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> 220 Please visit http://sourceforge.net/projects/filezilla/
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> SSH-2.0-JSCH-0.1.44
(000033)9/12/2011 13:08:53 PM - (not logged in) (127.0.0.1)> 500 Syntax error, command unrecognized.
(000033)9/12/2011 13:09:54 PM - (not logged in) (127.0.0.1)> 421 Login time exceeded. Closing control connection.
(000033)9/12/2011 13:09:54 PM - (not logged in) (127.0.0.1)> disconnected.

我不明白为什么 JSch 程序发出 SSH-2.0-JSCH-0.1.44 命令,然后通信被关闭。我们如何避免这种情况?

最佳答案

JSch 不是 FTP 客户端。JSch 是 SSH 客户端(包含 SFTP 实现)。

SSH 协议(protocol)是一种允许安全连接到服务器的协议(protocol),用于 shell 访问、文件传输或端口转发。为此,服务器必须有一个 SSH 服务器(通常在端口 22 上,但可能会有所不同)。 SFTP 是一种二进制文件传输协议(protocol),通常通过 SSH 隧道传输,与 FTP 无关(名称除外)。

如果你想使用 JSch 下载/上传文件,你需要在你的计算机上安装并激活 SSH/SFTP 服务器(对应你要访问的计算机)。

对于 FTP,您必须使用其他 Java 库(从这里的问题来看,Apache Commons FTPClient 似乎很有名)。

顺便说一下,JSch 的已知主机 文件是一个列出 SSH 主机公钥的文件,而不是列出其 IP 地址的文件(这是您尝试访问的 Windows 配置文件)在这里供应)。

关于java - 如何使用 JSch 访问 FTP 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7393545/

相关文章:

go - 我如何使用 Atom.io 让 go-plus 知道我正在服务器上开发?

VIM - 将本地文件夹映射到远程文件夹

java - org.hibernate.hql.ast.QuerySyntaxException 异常

java - 为什么 jboss 服务无法启动以及为什么我的休息时出现 404 错误?

java - session 未创建,此版本的 ChromeDriver 仅支持 Chrome 版本 74

android ftp上传已停止错误

java - 如何在 Neo4j for java 中传递动态生成的属性名称和值列表?

ios - 从 FTP 服务器下载文件并将其内容解码到 iOS 应用程序

c# - C#递归上传到FTP服务器

linux - 在 SFTP 中下载或移动目录? -r 给出非法参数