简体   繁体   English

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

[英]How can I access an FTP server with JSch?

I installed FileZilla FTP Server on my local Windows 7 machine.我在本地 Windows 7 机器上安装了 FileZilla FTP 服务器。 I also installed FileZilla FTP client on the same machine.我还在同一台机器上安装了 FileZilla FTP 客户端。 Connection is successfull between both of them confirming the server and client partnership exists.它们之间的连接成功,确认服务器和客户端伙伴关系存在。

I wrote a small quick and dirtry Jsch program for connecting to the FileZilla FTP server and below is the program:我写了一个小的快速和肮脏的 Jsch 程序来连接到 FileZilla FTP 服务器,下面是程序:

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

I tried running this program and below is the FTP log:我试着运行这个程序,下面是 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 - (未登录) (127.0.0.1)> 已连接,正在发送欢迎信息...
(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 - (未登录) (127.0.0.1)> 220-FileZilla Server 版本 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 - (未登录) (127.0.0.1)> 220-由 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 - (未登录) (127.0.0.1)> 220 请访问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 - (未登录) (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:08:53 PM -(未登录)(127.0.0.1)> 500 语法错误,无法识别命令。
(000033)9/12/2011 13:09:54 PM - (not logged in) (127.0.0.1)> 421 Login time exceeded. (000033)9/12/2011 13:09:54 PM - (未登录) (127.0.0.1)> 421 超过登录时间。 Closing control connection.关闭控制连接。
(000033)9/12/2011 13:09:54 PM - (not logged in) (127.0.0.1)> disconnected. (000033)9/12/2011 13:09:54 PM -(未登录)(127.0.0.1)> 断开连接。

I don't understand why the JSch program is issuing SSH-2.0-JSCH-0.1.44 command and the communication is then turned down.我不明白为什么 JSch 程序发出SSH-2.0-JSCH-0.1.44命令然后通信被拒绝。 How do we avoid this?我们如何避免这种情况?

JSch is not an FTP client. JSch 不是 FTP 客户端。 JSch is an SSH client (with an included SFTP implementation). JSch 是一个 SSH 客户端(包含一个 SFTP 实现)。

The SSH protocol is a protocol to allow secure connections to a server, for shell access, file transfer or port forwarding. SSH 协议是一种允许安全连接到服务器的协议,用于外壳访问、文件传输或端口转发。 For this, the server must have an SSH server (usually on port 22, but that can vary).为此,服务器必须有一个SSH 服务器(通常在端口 22 上,但可能会有所不同)。 SFTP is a binary file transfer protocol which is usually tunneled over SSH, and not related to FTP (other than by name). SFTP 是一种二进制文件传输协议,通常通过 SSH 进行隧道传输,与 FTP 无关(除了名称之外)。

If you want to use JSch to download/upload files, you need to install and activate an SSH/SFTP server on your computer (respective the computer you want to access).如果您想使用JSch下载/上传文件,您需要在您的计算机(与您要访问的计算机)上安装并激活一个SSH/SFTP服务器。

For FTP, you have to use other Java libraries (Apache Commons FTPClient seems to be famous, from the questions here).对于 FTP,您必须使用其他 Java 库(Apache Commons FTPClient 似乎很有名,来自这里的问题)。

By the way, the known hosts file for JSch is a file listing the public keys of the SSH hosts, not the file listing their IP addresses (which is the Windows config file you are trying to supply here).顺便说一下,JSch 的已知主机文件是一个列出 SSH 主机公钥的文件,而不是列出它们的 IP 地址的文件(这是您尝试在此处提供的 Windows 配置文件)。

Use Apache commons-net FTP library .使用Apache commons-net FTP 库

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPReply;

public class FTPConnectionCode {

    public static void main(String[] args) {
        String server = "www.website.com";
       // generally ftp port is 21
        int port = 21;
        String user = "ftpusername";
        String pass = "ftppassword";

        FTPClient ftpClient = new FTPClient();

        try {

            ftpClient.connect(server, port);
            showServerReply(ftpClient);

            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("Connect failed");
                return;
            }

            boolean success = ftpClient.login(user, pass);
            showServerReply(ftpClient);

            if (!success) {
                System.out.println("Could not login to the server");
                return;
            }

            // Changes working directory
            success = ftpClient.changeWorkingDirectory("/dir");
            showServerReply(ftpClient);

            if (success) {
                System.out.println("Successfully changed working directory.");
            } else {
                System.out.println("Failed to change working directory. See server's reply.");
            }

            // logs out
            ftpClient.logout();
            ftpClient.disconnect();

        } catch (IOException ex) {
            System.out.println("Oops! Something wrong happened");
            ex.printStackTrace();
        }
    }

    private static void showServerReply(FTPClient ftpClient) {
        String[] replies = ftpClient.getReplyStrings();
        if (replies != null && replies.length > 0) {
            for (String aReply : replies) {
                System.out.println("SERVER: " + aReply);
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM