如何在 Android 中创建 SFTP 连接?

发布于 2025-01-07 14:42:54 字数 292 浏览 3 评论 0 原文

我想开发一个到服务器的安全 FTP 连接并使用 Android 发送/检索文件。

我做了很多研究,发现了很多不同的方法,所以我不知道这个项目需要哪些工具和库。

  • 我需要什么样的服务器? (我听说过 OpenSSH
  • 如何让它在我的 Windows 系统上工作?
  • 我必须使用哪些库?

我正在使用 Windows 和 Eclipse。

I want to develop a secured FTP Connection to a server and send/retrieve files using Android.

I have researched a lot and found many different ways, so I don't know which tools and libraries I need for this project.

  • What kind of server will I need? (I heard about OpenSSH)
  • How can I make it work on my Windows system?
  • Which libraries will I have to use?

I'm using Windows and Eclipse.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

↙厌世 2025-01-14 14:42:54

您可以只运行 SFTP 服务器并在 Android 设备上使用 SFTP 客户端; FileZilla OpenSSHCerberus 等 - 有数百万个 SFTP 服务器。

安装它,并设置身份验证(用户名和密码、证书,无论您喜欢什么)。确保 SFTP 端口开放入站 - 所有这些软件包都允许您定义要使用的端口。

对于 Android,只需安装一个 SFTP 客户端,例如 Lysesoft 的 AndFTP 并弹出在服务器的地址和身份验证凭据中。

或者,如果您确实想对文件执行一些有用的操作,Android 内置了 FTP 库 - 请参阅 DroidFtp 项目。

You can just run an SFTP server and use an SFTP client on your Android device; FileZilla, OpenSSH, Cerberus, etc. - there are millions of SFTP servers.

Install it, and set up authentication (username and password, certificate, whatever you prefer). Ensure SFTP port is open inbound - all these packages let you define the port you wish to use.

For Android, just install an SFTP client like Lysesoft's AndFTP and pop in the address and authentication credentials for your server.

Or if you are actually wanting to do something useful with the files, Android has FTP libraries built in - see the DroidFtp project.

美男兮 2025-01-14 14:42:54
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;
}
}
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;
}
}
浪漫之都 2025-01-14 14:42:54
   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();
        }*/
   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();
        }*/
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文