SSH2纯Java实现—JSch介绍和使用

介绍:
JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。同时该项目也提供一个J2ME版本用来在手机上直连SSHD服务器。
 
使用:
pom.xml文件引入相关依赖
 1 <dependency>
 2     <groupId>commons-io</groupId>
 3     <artifactId>commons-io</artifactId>
 4     <version>2.6</version>
 5 </dependency>
 6 <dependency>
 7     <groupId>com.jcraft</groupId>
 8     <artifactId>jsch</artifactId>
 9     <version>0.1.55</version>
10 </dependency>

代码实现

  1 package cn.zxj.gkxt.core.util;
  2 
  3 
  4 import com.jcraft.jsch.*;
  5 import org.slf4j.Logger;
  6 import org.slf4j.LoggerFactory;
  7 
  8 
  9 import java.io.File;
 10 import java.io.FileInputStream;
 11 import java.io.IOException;
 12 import java.io.InputStream;
 13 import java.util.*;
 14 
 15 
 16 /**
 17 * JSch(Java Secure Channel)
 18 * SSH2纯Java实现
 19 * 连接至SSH服务器
 20 */
 21 public class JschUtils {
 22     private static final Logger LOG = LoggerFactory.getLogger(JschUtils.class.getName());
 23 
 24 
 25     /**
 26      * main方法
 27      * 本地开发
 28      * @param args 输入参数
 29      */
 30     public static void main(String[] args) {
 31         String userName = System.getProperty("user.name");
 32 
 33         ChannelSftp sftp = connect("10.194.61.92", 22, "tomcat", "Gzyqzxj092@tomcatlinserver");
 34 
 35         
 36         // 上传文件至SFTP指定目录
 37         if (1 == 1) {
 38             upload("/home/tomcat/gkxt/static/sftpLibrary", "C:\\Users\\" + userName + "\\Documents\\demo.jpg", sftp);
 39         }
 40     }
 41 
 42 
 43     /**
 44      * 连接SFTP服务器
 45      * @param host 主机
 46      * @param port 端口
 47      * @param username 用户名
 48      * @param password 密码
 49      * @return ChannelSftp
 50      */
 51     public static ChannelSftp connect(String host, int port, String username,
 52                                       String password) {
 53         ChannelSftp sftp = null;
 54 
 55 
 56         try {
 57             // 初始化JCsh对象
 58             JSch jsch = new JSch();
 59             // 由用户名 | 主机ip | 端口号获取单个Session对象
 60             Session sshSession = jsch.getSession(username, host, port);
 61             LOG.info("Session created.");
 62 
 63 
 64             // 设置登录密码
 65             sshSession.setPassword(password);
 66 
 67 
 68             // 初始化Properties对象
 69             Properties sshConfig = new Properties();
 70             sshConfig.put("StrictHostKeyChecking", "no");
 71 
 72 
 73             // 为Session对象设置properties
 74             sshSession.setConfig(sshConfig);
 75             // 设置timeout
 76             sshSession.setTimeout(5000);
 77             sshSession.connect();
 78             LOG.info("Session connected.");
 79             LOG.info("Opening Channel.");
 80 
 81 
 82             // 指定获取Channel连接方式
 83             Channel channel = sshSession.openChannel("sftp");
 84             channel.connect();
 85             sftp = (ChannelSftp) channel;
 86             LOG.info("Connected to " + host + ".");
 87         } catch (Exception e) {
 88             e.printStackTrace();
 89             throw new RuntimeException(e);
 90         }
 91         return sftp;
 92     }
 93 
 94 
 95     /**
 96      * 上传文件
 97      * @param directory 上传的目录
 98      * @param uploadFile 要上传的文件
 99      * @param sftp ChannelSftp
100      */
101     public static void upload(String directory, String uploadFile, ChannelSftp sftp) {
102         mkDir(directory, sftp);
103         InputStream in = null;
104         try {
105             sftp.cd(directory);
106             File file = new File(uploadFile);
107             in = new FileInputStream(file);
108             sftp.put(new FileInputStream(file), file.getName());
109         } catch (Exception e) {
110             e.printStackTrace();
111         } finally {
112             try {
113                 assert in != null;
114                 in.close();
115             } catch (IOException e) {
116                 e.printStackTrace();
117             }
118         }
119     }
120 
121 
122     /**
123      * 下载文件
124      * @param directory 目录
125      * @param downloadFile 下载的文件
126      * @param sftp ChannelSftp
127      */
128     public static InputStream download(String directory, String downloadFile,
129                                        ChannelSftp sftp) {
130         InputStream in = null;
131         try {
132             sftp.cd(directory);
133             in = sftp.get(downloadFile);
134         } catch (Exception e) {
135             e.printStackTrace();
136             throw new RuntimeException(e);
137         }
138         return in;
139     }
140 
141 
142     /**
143      * 删除文件
144      * @param directory 文件所在目录
145      * @param deleteFile 要删除的文件
146      * @param sftp ChannelSftp
147      */
148     public static void delete(String directory, String deleteFile, ChannelSftp sftp) {
149         try {
150             sftp.cd(directory);
151             sftp.rm(deleteFile);
152         } catch (Exception e) {
153             e.printStackTrace();
154             throw new RuntimeException(e);
155         }
156     }
157 
158 
159     /**
160      * 列出目录下的文件
161      * @param directory 要列出的目录
162      * @param sftp ChannelSftp
163      * @return Vector(动态数组)
164      * @throws SftpException Sftp异常
165      */
166     public static Vector listFiles(String directory, ChannelSftp sftp) throws SftpException {
167         return sftp.ls(directory);
168     }
169 
170 
171 
172     /**
173      * 获取目录名称
174      * @param ls 目录数组
175      * @return 目录名称集合
176      */
177     public static List<String> buildFiles(Vector ls) {
178         if (ls != null) {
179             List<String> list = new ArrayList<>();
180             for (Object l : ls) {
181                 ChannelSftp.LsEntry f = (ChannelSftp.LsEntry) l;
182                 String nm = f.getFilename();
183                 if (".".equals(nm) || "..".equals(nm)) {
184                     continue;
185                 }
186                 list.add(nm);
187             }
188 
189 
190             return list;
191         }
192 
193 
194         return null;
195     }
196 
197 
198     /**
199      * 打开指定目录
200      * @param directory 目录
201      * @return boolean
202      */
203     public static boolean openDir(String directory, ChannelSftp sftp) {
204         try {
205             sftp.cd(directory);
206             return true;
207         } catch (SftpException e) {
208             return false;
209         }
210     }
211 
212 
213     /**
214      * 按指定路径创建文件夹
215      * @param dirName 文件夹路径
216      * @param sftp ChannelSftp
217      */
218     public static void mkDir(String dirName, ChannelSftp sftp) {
219         String[] dirs = dirName.split("/");
220         try {
221             String now = sftp.pwd();
222             sftp.cd("/");
223             for (String dir : dirs) {
224                 if (StringUtils.isNotEmpty(dir)) {
225                     boolean dirExists = openDir(dir, sftp);
226                     if (!dirExists) {
227                         sftp.mkdir(dir);
228                         sftp.cd(dir);
229                     }
230                 }
231             }
232             sftp.cd(now);
233         } catch (SftpException e) {
234             e.printStackTrace();
235         }
236     }
237 }

 

posted @ 2020-09-26 10:33  JKLOPPdream  阅读(2168)  评论(0编辑  收藏  举报