Java使用Sftp实现对跨服务器上传、下载、打包、写入相关操作

1、Maven引入jar

1<dependency> 2 <groupId>com.jcraft</groupId> 3 <artifactId>jsch</artifactId> 4 <version>0.1.54</version> 5 </dependency>

2、Test类

1package com.tandaima.pub; 2 3 4import java.io.*; 5import java.util.Properties; 6 7import com.jcraft.jsch.*; 8 9 10/** 11 * User longpizi 12 * Date: 2019/10/30 13 * Time: 14:40 14 */ 15public class SftpUtil { 16 public static final String CHANNELTYPE_SFTP="sftp"; 17 public static final String CHANNELTYPE_EXEC="exec"; 18 private Session session;//会话 19 private Channel channel;//连接通道 20 private ChannelSftp sftp;// sftp操作类 21 private JSch jsch; 22 protected static String host=getLinuxParam()[0]; 23 protected static String port=getLinuxParam()[1]; 24 protected static String user=getLinuxParam()[2]; 25 protected static String password=getLinuxParam()[3]; 26 27 private static String[] getLinuxParam(){ 28 Properties props=new Properties();//读取文件类型创建对象。 29 try { 30 ClassLoader classLoader = SftpUtil.class.getClassLoader();// 读取属性文件 31 InputStream in = classLoader.getResourceAsStream("linux.properties"); 32 props.load(in); /// 加载属性列表 33 if(in!=null){ 34 in.close(); 35 } 36 } catch (Exception e) { 37 System.out.println("Linux连接参数异常:"+e.getMessage()); 38 } 39 String[] str={"","","",""}; 40 str[0]=props.getProperty("file.host"); 41 str[1]=props.getProperty("file.port"); 42 str[2]=props.getProperty("file.user"); 43 str[3]=props.getProperty("file.password"); 44 return str; 45 } 46 /** 47 * 断开连接 48 */ 49 public static void closeConnect(Session session, Channel channel, ChannelSftp sftp){ 50 if (null != sftp) { 51 sftp.disconnect(); 52 sftp.exit(); 53 sftp = null; 54 } 55 if (null != channel) { 56 channel.disconnect(); 57 channel = null; 58 } 59 if (null != session) { 60 session.disconnect(); 61 session = null; 62 } 63 System.out.println("连接已关闭"); 64 } 65 66 /** 67 * 连接ftp/sftp服务器 68 * 69 * @param sftpUtil70 */ 71 public static void getConnect(SftpUtil sftpUtil,String openChannelType) throws Exception { 72 Session session = null; 73 Channel channel = null; 74 75 JSch jsch = new JSch(); 76 session = jsch.getSession(user, host, Integer.parseInt(port)); 77 session.setPassword(password); 78 // 设置第一次登陆的时候提示,可选值:(ask | yes | no) 79 // 不验证 HostKey 80 session.setConfig("StrictHostKeyChecking", "no"); 81 try { 82 session.connect(); 83 } catch (Exception e) { 84 if (session.isConnected()) 85 session.disconnect(); 86 System.out.println("连接服务器失败"); 87 } 88 channel = session.openChannel(openChannelType); 89 try { 90 channel.connect(); 91 } catch (Exception e) { 92 if (channel.isConnected()) 93 channel.disconnect(); 94 System.out.println("连接服务器失败"); 95 } 96 sftpUtil.setJsch(jsch); 97 if(openChannelType.equals(CHANNELTYPE_SFTP)){ 98 sftpUtil.setSftp((ChannelSftp) channel); 99 } 100 sftpUtil.setChannel(channel); 101 sftpUtil.setSession(session); 102 103 } 104 105 106 /** 107 * 上传文件 108 * 109 * @param directory 上传的目录-相对于SFPT设置的用户访问目录 110 * @param uploadFile 要上传的文件全路径 111 */ 112 public static boolean upload(String directory, String uploadFile) { 113 boolean resultState=false; 114 SftpUtil sftpUtil = new SftpUtil(); 115 try{ 116 getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接 117 Session session = sftpUtil.getSession(); 118 Channel channel = sftpUtil.getChannel(); 119 ChannelSftp sftp = sftpUtil.getSftp();// sftp操作类 120 try { 121 sftp.cd(directory); //进入目录 122 } catch (SftpException sException) { 123 if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) { //指定上传路径不存在 124 sftp.mkdir(directory);//创建目录 125 sftp.cd(directory); //进入目录 126 } 127 } 128 File file = new File(uploadFile); 129 InputStream in = new FileInputStream(file); 130 sftp.put(in, file.getName()); 131 in.close(); 132 closeConnect(session, channel, sftp); 133 resultState=true; 134 }catch (Exception e){ 135 System.out.println("上传文件异常"); 136 } 137 return resultState; 138 } 139 140 /** 141 * 获取已连接的Sftp 142 * @return SftpUtil 143 */ 144 public static SftpUtil getConnectSftp(){ 145 SftpUtil sftpUtil=new SftpUtil(); 146 try { 147 getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接 148 return sftpUtil; 149 }catch (Exception e){ 150 System.out.println("下载文件异常"); 151 } 152 return null; 153 } 154 155 /** 156 * 删除文件 157 * @param directory 要删除文件所在目录 158 * @param deleteFile 要删除的文件 159 */ 160 public static boolean delete(String directory, String deleteFile){ 161 boolean resultState=false; 162 SftpUtil sftpUtil=new SftpUtil(); 163 try { 164 getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接 165 Session session = sftpUtil.getSession(); 166 Channel channel = sftpUtil.getChannel(); 167 ChannelSftp sftp = sftpUtil.getSftp();// sftp操作类 168 sftp.cd(directory); //进入的目录应该是要删除的目录的上一级 169 sftp.rm(deleteFile);//删除目录 170 closeConnect(session,channel,sftp); 171 resultState=true; 172 }catch (Exception e){ 173 System.out.println("删除文件异常"); 174 } 175 return resultState; 176 } 177 178 /** 179 JSch有三种文件传输模式: 180 (1)OVERWRITE:完全覆盖模式。JSch的默认文件传输模式,传输的文件将覆盖目标文件。 181 (2)APPEND:追加模式。如果目标文件已存在,则在目标文件后追加。 182 (3)RESUME:恢复模式。如果文件正在传输时,由于网络等原因导致传输中断,则下一次传输相同的文件 183 时,会从上一次中断的地方续传。 184 */ 185 /** 186 * 追加文件内容 187 * @param remoteFile 原文件路径 188 * @param in 追加内容 189 * @return true成功,false失败 190 */ 191 public static boolean appendFileContent(String remoteFile, InputStream in){ 192 boolean resultState=false; 193 SftpUtil sftpUtil = new SftpUtil(); 194 try{ 195 getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接 196 Session session = sftpUtil.getSession(); 197 Channel channel = sftpUtil.getChannel(); 198 ChannelSftp sftp = sftpUtil.getSftp();// sftp操作类 199 OutputStream out = sftp.put(remoteFile, ChannelSftp.APPEND); 200 int bufferSize=1024; 201 byte[] buff = new byte[bufferSize]; // 设定每次传输的数据块大小 202 int read; 203 if (out != null) { 204 do { 205 read = in.read(buff, 0, buff.length); 206 if (read > 0) { 207 out.write(buff, 0, read); 208 } 209 out.flush(); 210 } while (read >= 0); 211 } 212 if(out!=null){ 213 out.close(); 214 } 215 closeConnect(session, channel, sftp); 216 resultState=true; 217 }catch (Exception e){ 218 System.out.println("写入文件异常"); 219 } 220 return resultState; 221 } 222 223 /** 224 * 创建文件 225 * @param fileDir 文件路径 226 * @param fileName 文件名称 227 * @return 228 */ 229 public static boolean createFile(String fileDir,String fileName){ 230 try{ 231 execute("mkdir -p "+fileDir+"\n" + 232 "touch "+fileDir+"/"+fileName); 233 }catch (Exception e){ 234 return false; 235 } 236 return true; 237 } 238 239 /** 240 * 创建文件夹 241 * @param fileDir 文件路径 242 * @return true成功/false失败 243 */ 244 public static boolean createFileDir(String fileDir){ 245 try{ 246 execute("mkdir -p "+fileDir+""); 247 }catch (Exception e){ 248 return false; 249 } 250 return true; 251 } 252 253 /** 254 * 压缩文件夹为ZIP 255 * @param fileDir 文件路径 256 * @param fileName 文件名称 257 * @param additionalName 压缩附加名 258 * @return 259 */ 260 public static boolean zipDir(String fileDir,String fileName,String additionalName){ 261 try{ 262 execute("cd "+fileDir+"\n" + 263 "zip -r "+fileDir+"/"+fileName+additionalName+".zip "+fileName); 264 }catch (Exception e){ 265 return false; 266 } 267 return true; 268 } 269 270 /** 271 * 获取文件大小 单位(K) 272 * @param fileDir 文件路径 273 * @return 文件大小 274 */ 275 public static long getFileSize(String fileDir){ 276 return Long.parseLong(execute("ls -l "+fileDir+" | awk '{ print $5 }'")); 277 } 278 /** 279 * 执行liunx 命令 280 * @param command 命令内容 281 * @return 命令输出 282 */ 283 private static String execute(String command){ 284 SftpUtil sftpUtil=new SftpUtil(); 285 StringBuffer strBuffer=new StringBuffer(); 286 try { 287 getConnect(sftpUtil,CHANNELTYPE_EXEC); 288 // Create and connect session. 289 Session session = sftpUtil.getSession(); 290 291 // Create and connect channel. 292 Channel channel = session.openChannel("exec"); 293 ((ChannelExec) channel).setCommand(command); 294 295 channel.setInputStream(null); 296 BufferedReader input = new BufferedReader(new InputStreamReader(channel 297 .getInputStream())); 298 299 channel.connect(); 300 System.out.println("命令: " + command); 301 // 获取命令的输出 302 String line; 303 while ((line = input.readLine()) != null) { 304 strBuffer.append(line); 305 } 306 input.close(); 307 closeConnect(session,channel,null); 308 } catch (Exception e) { 309 e.printStackTrace(); 310 } 311 return strBuffer.toString(); 312 } 313// public static void main(String[] args) throws FileNotFoundException { 314// String window_dir="C:\\Users\XXX\\Desktop\\test\\test.txt"; 315// String liunx_dir="/usr/local/longpizi"; 316// try { 317//// System.out.println(upload(liunx_dir,window_dir)); 318//// System.out.println(download(liunx_dir,"test.txt","C:\\Users\\XXX\\Desktop\\test")); 319//// System.out.println(delete(liunx_dir,"test.txt")); 320// 321//// InputStream inputStream = new ByteArrayInputStream("this is test".getBytes()); 322//// System.out.println(appendFileContent(liunx_dir+"/test.txt",inputStream)); 323// 324//// String command="touch /usr/local/longlin/longpizi.sh\nmkdir -p sss"; 325//// System.out.println(execute(command)); 326// 327//// System.out.println(createFile("/usr/local/longlin/test/sfdsfdf","sss.txt")); 328// } catch (Exception e) { 329// e.printStackTrace(); 330// } 331// } 332 333 public JSch getJsch() { 334 return jsch; 335 } 336 337 public void setJsch(JSch jsch) { 338 this.jsch = jsch; 339 } 340 341 public Session getSession() { 342 return session; 343 } 344 345 public void setSession(Session session) { 346 this.session = session; 347 } 348 349 public Channel getChannel() { 350 return channel; 351 } 352 353 public void setChannel(Channel channel) { 354 this.channel = channel; 355 } 356 357 public ChannelSftp getSftp() { 358 return sftp; 359 } 360 361 public void setSftp(ChannelSftp sftp) { 362 this.sftp = sftp; 363 } 364}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )