Java客户端,无需密码即可连接SFTP服务器

时间:2019-05-23 10:44:38

标签: java sftp

我只需要使用没有密码的用户名连接SFTP主机。有没有带有avove功能的Java客户端?请分享

2 个答案:

答案 0 :(得分:0)

Apache Commons VFS可以与SFTP一起使用。

String user="your username";
String url="your domain/path/fileName";

StandardFileSystemManager manager = new StandardFileSystemManager();
try {
    manager.init();

    String sftpUri = "sftp://" + user +  "@" + url;

    manager.addProvider("ram-ext", new RamFileProvider());
    RamFileObject localFile = (RamFileObject)manager.resolveFile("ram-ext:///root/file.txt");
    try(OutputStream out = localFile.getOutputStream()){

        //TODO:write to the outputStream
    }

    // Create remote file object
    FileObject remoteFile = manager.resolveFile(sftpUri,createDefaultOptions());

    // Copy local file to sftp server
    remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
}
catch(Exception ex) {
    ex.printStackTrace();
}
finally {
    manager.close();
}

public static FileSystemOptions createDefaultOptions() throws FileSystemException {
    // Create SFTP options
    FileSystemOptions opts = new FileSystemOptions();

    // SSH Key checking
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

    /*
     * Using the following line will cause VFS to choose File System's Root
     * as VFS's root. If I wanted to use User's home as VFS's root then set
     * 2nd method parameter to "true"
     */
    // Root directory set to user home
    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);

    // Timeout is count by Milliseconds
    SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

    return opts;
}

答案 1 :(得分:0)

您不是要创建会话,

尝试使用此代码。还要检查端口号是否正确,有时可能与22不同。

private static final String SFTP_HOST = "100.100.100.100"; // SFTP Host Name or SFTP Host IP Address
private static final int SFTP_PORT = 22; // SFTP Port Number
private static final String SFTP_USERNAME = "root"; // User Name

public void login() throws Exception {
    Channel channel = null;
    try {
        JSch jsch = new JSch();
        Session m_Session = jsch.getSession(SFTP_USERNAME, SFTP_HOST, SFTP_PORT);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        m_Session.setConfig(config);

        m_Session.connect(); // Create SFTP Session

        channel = m_Session.openChannel("sftp");
        channel.connect();
        ChannelSftp m_channelSftp = (ChannelSftp) channel;
    } catch (Exception e) {
        e.printStackTrace();
    }
}
相关问题