Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用JSch访问FTP服务器?_Java_Ftp_Sftp_Jsch - Fatal编程技术网

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

Java 如何使用JSch访问FTP服务器?,java,ftp,sftp,jsch,Java,Ftp,Sftp,Jsch,我在本地Windows 7计算机上安装了FileZilla FTP服务器。 我还在同一台机器上安装了FileZilla FTP客户端。 两者之间的连接成功,确认服务器和客户端伙伴关系存在 我编写了一个小的快速直接的Jsch程序,用于连接FileZilla FTP服务器,下面是该程序: public class TestJSch { /** Creates a new instance of TestCommonsNet */ public TestJSch() { } /** * main

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

我编写了一个小的快速直接的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);
    }
}
}
我尝试运行此程序,下面是FTP日志:

(000033)2011年9月12日13:08:53下午-(未登录)(127.0.0.1)>已连接,正在发送欢迎消息…
(000033)2011年9月12日13:08:53下午-(未登录)(127.0.0.1)>220 FileZilla服务器版本0.9.39 beta
(000033)2011年12月9日13:08:53下午-(未登录)(127.0.0.1)>220由Tim Kosse(Tim。Kosse@gmx.de)
(000033)2011年9月12日13:08:53下午-(未登录)(127.0.0.1)>220请访问
(000033)2011年9月12日13:08:53下午-(未登录)(127.0.0.1)>SSH-2.0-JSCH-0.1.44
(000033)2011年9月12日13:08:53下午-(未登录)(127.0.0.1)>500语法错误,无法识别命令。
(000033)2011年9月12日13:09:54下午-(未登录)(127.0.0.1)>超过421登录时间。关闭控制连接。
(000033)2011年9月12日13:09:54下午-(未登录)(127.0.0.1)>已断开连接


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

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

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

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

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

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

使用


为了避免链接失效时信息丢失,从链接页面引用相关信息要比简单链接好得多。
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);
            }
        }
    }
}