2012-02-21 118 views
0

我想開發一個安全的FTP連接到服務器,並使用Android發送/檢索文件。如何在Android中創建SFTP連接?

我研究了很多,發現了很多不同的方法,所以我不知道我需要哪些工具和庫。

  • 我需要什麼樣的服務器? (我聽說過OpenSSH
  • 我該如何讓它在我的Windows系統上工作?
  • 我必須使用哪些庫?

我使用的是Windows和Eclipse。

+0

非常相關的問題,我喜歡你正在研究的概念。如果您有任何進展,請告訴我。我正在處理類似的問題。 – 2012-07-22 22:22:45

回答

2

您可以在Android設備上運行SFTP服務器並使用SFTP客戶端; FileZillaOpenSSH,Cerberus等 - 有數以百萬計的SFTP服務器。

安裝它,並設置身份驗證(用戶名和密碼,證書,無論你喜歡什麼)。確保入站的SFTP端口是開放的 - 所有這些軟件包允許您定義您希望使用的端口。

對於Android,只需安裝一個SFTP客戶端,如Lysesoft的AndFTP並彈出您的服務器的地址和身份驗證憑據。

或者,如果您實際上想要對文件進行一些有用的操作,則Android內置FTP庫 - 請參閱DroidFtp項目。

+0

感謝您的回答。但我實際上想要開發一個Android Prototype,它創建與Server的連接,並在設備和Server之間進行安全文件交換。 你有什麼想法嗎? – Johnny2012 2012-02-21 22:15:12

+1

你能解釋一下你的意思嗎?我所描述的將能夠創建到服務器的連接並安全地交換文件。你想在應用程序中做到這一點?如果是這樣,看看DroidFTP和Android的ftp庫。 – 2012-02-21 23:59:27

0
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; 
} 
}