如何使用JSch访问FTP服务器? [英] How can I access an FTP server with JSch?

查看:302
本文介绍了如何使用JSch访问FTP服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我写了一个小而快捷的杂项Jsch程序,用于连接FileZilla FTP服务器下面是该程序:

  public class TestJSch {

/ **创建一个新的实例TestCommonsNet * /
public TestJSch(){
}
$ b $ ** / **
* main - 单元测试程序
*
* @param args
*命令行参数
*
* /
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;

//
//首先创建一个JSch会话
//
JSch.setLogger(new MyLogger());
System.out.println(Creating session。);

JSch jsch = new JSch();

字符串knownHostsFilename =C:\\\\ Windows \\
jsch.setKnownHosts(knownHostsFilename);
jsch.addIdentity(identityfile);
会话会话=空;
频道频道=空;
ChannelSftp c = null;

//
//现在连接SFTP服务器到SFTP服务器
//
尝试{
//创建通过我们的用户名发送的会话和密码
session = jsch.getSession(ftpUserName,ftpHost,ftpPort);
System.out.println(Session created。);
session.setPassword(ftpPassword);
// Security.addProvider(new com.sun.crypto.provider.SunJCE());

// b
//设置严格的HostKeyChecking为no,所以我们不会得到
//未知的主机密钥异常
//
java.util .Properties config = new java.util.Properties();
config.put(StrictHostKeyChecking,no);
session.setConfig(config);
session.connect();
System.out.println(Session connected。);

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

//
//切换到远程目录
//
System.out.println(更改为FTP远程目录:
+ ftpRemoteDirectory);
c.cd(ftpRemoteDirectory);

//
//发送我们生成的文件
//
尝试{
文件f = new File(fileToTransmit);
System.out.println(将文件保存为远程文件名:
+ f.getName());
c.put(new FileInputStream(f),f.getName());
} catch(Exception e){
System.err
.println(存储远程文件失败。+ e.toString());
throw e;
}

//
//断开与FTP服务器的连接
//
尝试{
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(新整数(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 - (未登录)(127.0 .0.1)>连接,发送欢迎信息...

(000033)9/12/2011 13:08:53 PM - (not logged in)(127.0.0.1)> 220-FileZilla服务器版本0.9.39测试版 -
(000033)9/12/2011 13:08:53 - (未登录)(127.0.0.1)> 220由Tim Kosse撰写(Tim.Kosse@gmx。 de)

(000033)9/12/2011 13:08:53 - (未登录)(127.0.0.1)> 220请访问 http://sourceforge.net/projects/filezilla/

(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 - (未登录)(127.0.0.1)> 500语法错误,命令无法识别。

(000033)9/12/2011 13:09:54 PM - (未登录)(127.0.0.1)> 421登录时间超时。关闭控制连接。
(000033)9/12/2011 13:09:54 PM - (未登录)(127.0.0.1)>已断开连接。




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

解决方案

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

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



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



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



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


I installed FileZilla FTP Server on my local Windows 7 machine. I also installed FileZilla FTP client on the same machine. 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:

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:

(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.

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. How do we avoid this?

解决方案

JSch is not an FTP client. JSch is an SSH client (with an included SFTP implementation).

The SSH protocol is a protocol to allow secure connections to a server, for shell access, file transfer or port forwarding. For this, the server must have an SSH server (usually on port 22, but that can vary). SFTP is a binary file transfer protocol which is usually tunneled over SSH, and not related to FTP (other than by name).

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).

For FTP, you have to use other Java libraries (Apache Commons FTPClient seems to be famous, from the questions here).

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访问FTP服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆