Java中com.jcraft.jsch.ChannelSftp讲解

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。

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import com.jcraft.jsch.Channel;
  6. import com.jcraft.jsch.ChannelExec;
  7. import com.jcraft.jsch.JSch;
  8. import com.jcraft.jsch.JSchException;
  9. import com.jcraft.jsch.Session;
  10. public class ShellUtils {
  11. private static JSch jsch;
  12. private static Session session;
  13. /**
  14. * 连接到指定的IP
  15. *
  16. * @throws JSchException
  17. */
  18. public static void connect(String user, String passwd, String host) throws JSchException {
  19. jsch = new JSch();
  20. session = jsch.getSession(user, host, 22);
  21. session.setPassword(passwd);
  22. java.util.Properties config = new java.util.Properties();
  23. config.put("StrictHostKeyChecking", "no");
  24. session.setConfig(config);
  25. session.connect();
  26. }
  27. /**
  28. * 执行相关的命令
  29. * @throws JSchException
  30. */
  31. public static void execCmd(String command, String user, String passwd, String host) throws JSchException {
  32. connect(user, passwd, host);
  33. BufferedReader reader = null;
  34. Channel channel = null;
  35. try {
  36. while (command != null) {
  37. channel = session.openChannel("exec");
  38. ((ChannelExec) channel).setCommand(command);
  39. channel.setInputStream(null);
  40. ((ChannelExec) channel).setErrStream(System.err);
  41. channel.connect();
  42. InputStream in = channel.getInputStream();
  43. reader = new BufferedReader(new InputStreamReader(in));
  44. String buf = null;
  45. while ((buf = reader.readLine()) != null) {
  46. System.out.println(buf);
  47. }
  48. }
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. } catch (JSchException e) {
  52. e.printStackTrace();
  53. } finally {
  54. try {
  55. reader.close();
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }
  59. channel.disconnect();
  60. session.disconnect();
  61. }
  62. }
  63. }
上一篇:sparkR读取csv文件


下一篇:Mysql引擎中MyISAM和InnoDB的区别有哪些?