如何在Android中创建SFTP连接?

3
我想开发一个安全的FTP连接到服务器,并使用Android发送/检索文件。
我已经做了很多研究并找到了许多不同的方法,因此我不知道这个项目需要哪些工具和库。
  • 我需要什么样的服务器?(我听说过OpenSSH
  • 如何在我的Windows系统上使其正常工作?
  • 我将需要使用哪些库?
我正在使用Windows和Eclipse。

1
非常相关的问题,我喜欢你正在处理的概念。如果你有任何进展,请告诉我。我正在处理一个类似的问题。 - tony gil
3个回答

6
您可以运行SFTP服务器,并在Android设备上使用SFTP客户端; FileZilla, OpenSSH, Cerberus等-有数百万个SFTP服务器。
安装它,并设置认证(用户名和密码,证书或其他你偏好的方式)。确保入站SFTP端口已打开-所有这些软件包都允许您定义所需使用的端口。
对于Android,只需安装像Lysesoft的SFTP客户端AndFTP并输入服务器的地址和认证凭据即可。

如果你想要对这些文件做一些有用的事情,Android内置了FTP库 - 参见DroidFtp项目。


谢谢您的回答。但是我实际上想开发一个Android原型,它可以与服务器建立连接,并且设备和服务器之间进行安全文件交换。您有任何想法吗? - Johnny2012
1
你能解释一下你的意思吗?我所描述的将能够创建到服务器的连接并安全地交换文件。你想在应用程序中实现它吗?如果是这样,请查看DroidFTP和Android ftp库。 - Rory Alsop

2
public class SFTPClient {

Context context;
private static String host = ServerUrl.FTP_HOST;
private static String username = ServerUrl.FTP_USERNAME;
private static String remoteDirectory = "/home/ubuntu/";
public static File photo_file;

/**
 * http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/
 * 
 * @param server
 * @param userName
 * @param openSSHPrivateKey
 * @param remoteDir
 * @param localDir
 * @param localFileName
 * @throws IOException
 */
public static void sftpUploadFile_keyAuthentication_jsch(final Context con,
        final File f) throws IOException {
    photo_file = f;

    new AsyncTask<Void, Void, Void>() {
        private File createFileFromInputStream(InputStream inputStream,
                String fileName) {
            File keyFile = null;
            try {
                keyFile = new File(con.getCacheDir() + "/" + fileName);
                if (!keyFile.exists() || !keyFile.canRead()) {
                    OutputStream outputStream = new FileOutputStream(
                            keyFile);
                    byte buffer[] = new byte[1024];
                    int length = 0;

                    while ((length = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, length);
                    }

                    outputStream.close();
                    inputStream.close();
                }
            } catch (IOException e) {
                // Logging exception
                Log.e("error", e + "");

            }

            return keyFile;
        }

        @Override
        protected Void doInBackground(Void... params) {
            FileInputStream fis = null;
            OutputStream os = null;
            try {
                JSch jsch = new JSch();

                AssetManager am = con.getAssets();
                InputStream inputStream = am.open("splash_openssh.ppk");
                File file = createFileFromInputStream(inputStream,
                        "splash_openssh.ppk");

                if (file.exists()) {
                    System.out.println(file + "");
                } else {
                    System.out.println(file + "");
                }

                String path = file + "";
                jsch.addIdentity(path);

                Session session = jsch.getSession(username, host, 22);
                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.connect();
                System.out.println("JSch JSch Session connected.");
                System.out.println("Opening Channel.");
                System.gc();
                ChannelSftp channelSftp = null;
                channelSftp = (ChannelSftp) session.openChannel("sftp");
                channelSftp.connect();
                channelSftp.cd(remoteDirectory);

                long currentFilelength = f.length();
                fis = new FileInputStream(f);
                channelSftp.put(fis, f.getName());


                Log.w("Start Upload Process", "Start Upload Process");

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (SftpException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return null;
        };
    }.execute();

}

/**
 * 
 * http://kodehelp.com/java-program-for-downloading-file-from-sftp-server/
 * 
 * @param server
 * @param userName
 * @param openSSHPrivateKey
 * @param remoteDir
 * @param remoteFile
 * @param localDir
 * @throws IOException
 */
public static File sftpDownloadFile_keyAuthentication_jsch(final Context con)
        throws IOException {

    new AsyncTask<Void, Void, Void>() {

        private File createFileFromInputStream(InputStream inputStream,
                String fileName) {
            File keyFile = null;
            try {
                keyFile = new File(con.getCacheDir() + "/" + fileName);
                if (!keyFile.exists() || !keyFile.canRead()) {
                    OutputStream outputStream = new FileOutputStream(
                            keyFile);
                    byte buffer[] = new byte[1024];
                    int length = 0;

                    while ((length = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, length);
                    }

                    outputStream.close();
                    inputStream.close();
                }
            } catch (IOException e) {
                // Logging exception
                Log.e("error", e + "");

            }

            return keyFile;
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            File newFile = null;
            try {
                // JSch jsch = new JSch();
                // String password =
                // "/storage/sdcard0/Splash/splash_openssh.ppk";
                // System.out.println(password);
                // jsch.addIdentity(password);
                JSch jsch = new JSch();

                AssetManager am = con.getAssets();
                InputStream inputStream;

                inputStream = am.open("splash_openssh.ppk");

                File file = createFileFromInputStream(inputStream,
                        "splash_openssh.ppk");

                if (file.exists()) {
                    System.out.println(file + "");
                } else {
                    System.out.println(file + "");
                }

                String path = file + "";
                jsch.addIdentity(path);
                Session session = jsch.getSession(username, host, 22);
                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.connect();
                Channel channel = session.openChannel("sftp");
                channel.setOutputStream(System.out);
                channel.connect();
                ChannelSftp channelSftp = (ChannelSftp) channel;
                channelSftp.cd(remoteDirectory);

                byte[] buffer = new byte[1024];
                File mf = Environment.getExternalStorageDirectory();

                BufferedInputStream bis = new BufferedInputStream(
                        channelSftp.get("269-twitter.jpg"));
                newFile = new File(
                        Environment.getExternalStorageDirectory()
                                + "/Splash/upload/", "splash_img1.jpg");

                OutputStream os = null;

                os = new FileOutputStream(newFile);
                BufferedOutputStream bos = new BufferedOutputStream(os);
                int readCount;
                while ((readCount = bis.read(buffer)) > 0) {
                    System.out.println("Writing: ");
                    bos.write(buffer, 0, readCount);
                }
                bos.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (SftpException e) {
                e.printStackTrace();
            }
            return null;
        };
    }.execute();
    return null;

}

private static String FileSaveInLocalSDCard(File file) {
    // TODO Auto-generated method stub
    String imagePath = "";
    File mf = Environment.getExternalStorageDirectory();
    String storePath = mf.getAbsoluteFile() + "/Splash/upload/";

    File dirFile = new File(storePath);
    dirFile.mkdirs();
    File destfile = new File(dirFile, file.getName());
    imagePath = storePath + file.getName();
    try {
        boolean copyFileValue = copyFile(file, destfile);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return imagePath;
}

public static Boolean copyFile(File sourceFile, File destFile)
        throws IOException {
    if (!destFile.exists()) {
        destFile.createNewFile();

        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null)
                source.close();
            if (destination != null)
                destination.close();
        }
        return true;
    }
    return false;
}
}

1
   Connect SFTP :
                  try {
            JSch ssh = new JSch();
            session = ssh.getSession("hostusername", "host(ip or host name)", 22);
            session.setPassword("password");
            session.setConfig(config);
            session.connect();
            conStatus = session.isConnected();
            Log.e("Session", "is" + conStatus);
            channel = session.openChannel("sftp");
            channel.connect();

            ChannelSftp sftp = (ChannelSftp) channel;
            sftp.get("sshfile.txt", Environment.getExternalStorageDirectory().getPath() + "/sshfile.txt");
            } catch (JSchException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("Session", "is" + e);
        } catch (SftpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("Session", "is" + e);
        } /*catch (IOException e) {
            e.printStackTrace();
        }*/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接