http://blog.csdn.net/allen_zhao_2012/article/details/7941631
http://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html
http://xpenxpen.iteye.com/blog/2061869
http://blog.csdn.net/fyqcdbdx/article/details/23863793
http://blog.csdn.net/u013256816/article/details/52701563?utm_source=gold_browser_extension
SFTP是Secure File Transfer Protocol的縮寫,安全文件傳送協議。可以為傳輸文件提供一種安全的加密方法。SFTP 為 SSH的一部份,是一種傳輸文件到服務器的安全方式。SFTP是使用加密傳輸認證信息和傳輸的數據,所以,使用SFTP是非常安全的。但是,由於這種傳輸方式使用了加密/解密技術,所以傳輸效率比普通的FTP要低得多,如果您對網絡安全性要求更高時,可以使用SFTP代替FTP。
ChannelSftp類是JSch實現SFTP核心類,它包含了所有SFTP的方法,如:
put(): 文件上傳
get(): 文件下載
cd(): 進入指定目錄
ls(): 得到指定目錄下的文件列表
rename(): 重命名指定文件或目錄
rm(): 刪除指定文件
mkdir(): 創建目錄
rmdir(): 刪除目錄
等等(這里省略了方法的參數,put和get都有多個重載方法,具體請看源代碼,這里不一一列出。)
一個簡單的jsch鏈接Linux並執行命令的utils。
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import com.jcraft.jsch.Channel;
- import com.jcraft.jsch.ChannelExec;
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.JSchException;
- import com.jcraft.jsch.Session;
- public class ShellUtils {
- private static JSch jsch;
- private static Session session;
- /**
- * 連接到指定的IP
- *
- * @throws JSchException
- */
- public static void connect(String user, String passwd, String host) throws JSchException {
- jsch = new JSch();
- session = jsch.getSession(user, host, 22);
- session.setPassword(passwd);
- java.util.Properties config = new java.util.Properties();
- config.put("StrictHostKeyChecking", "no");
- session.setConfig(config);
- session.connect();
- }
- /**
- * 執行相關的命令
- * @throws JSchException
- */
- public static void execCmd(String command, String user, String passwd, String host) throws JSchException {
- connect(user, passwd, host);
- BufferedReader reader = null;
- Channel channel = null;
- try {
- while (command != null) {
- channel = session.openChannel("exec");
- ((ChannelExec) channel).setCommand(command);
- channel.setInputStream(null);
- ((ChannelExec) channel).setErrStream(System.err);
- channel.connect();
- InputStream in = channel.getInputStream();
- reader = new BufferedReader(new InputStreamReader(in));
- String buf = null;
- while ((buf = reader.readLine()) != null) {
- System.out.println(buf);
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSchException e) {
- e.printStackTrace();
- } finally {
- try {
- reader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- channel.disconnect();
- session.disconnect();
- }
- }
- }