设为首页 收藏本站
查看: 1183|回复: 0

[经验分享] ftp,sftp

[复制链接]

尚未签到

发表于 2016-6-7 10:32:19 | 显示全部楼层 |阅读模式
  package com.teradata.util;
  
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.net.URLEncoder;
  
  import org.apache.commons.io.IOUtils;
  import org.apache.commons.net.ftp.FTPClient;
  import org.apache.commons.net.ftp.FTPFile;
  
  public class FtpTest {
  public static void main(String[] args) {
  // testUpload();
  testDownload();
  }
  
  /**
  * FTP上传单个文件测试
  */
  public static void testUpload() {
  FTPClient ftpClient = new FTPClient();
  FileInputStream fis = null;
  
  try {
  ftpClient.connect("127.0.0.1");
  ftpClient.login("admin", "123");
  
  File srcFile = new File("C:\\new.gif");
  fis = new FileInputStream(srcFile);
  // 设置上传目录
  ftpClient.changeWorkingDirectory("/admin/pic");
  ftpClient.setBufferSize(1024);
  ftpClient.setControlEncoding("GBK");
  // 设置文件类型(二进制)
  ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  ftpClient.storeFile("3.gif", fis);
  } catch (IOException e) {
  e.printStackTrace();
  throw new RuntimeException("FTP客户端出错!", e);
  } finally {
  IOUtils.closeQuietly(fis);
  try {
  ftpClient.disconnect();
  } catch (IOException e) {
  e.printStackTrace();
  throw new RuntimeException("关闭FTP连接发生异常!", e);
  }
  }
  }
  
  /**
  * FTP下载单个文件测试
  */
  public static void testDownload1() {
  FTPClient ftpClient = new FTPClient();
  FileOutputStream fos = null;
  
  try {
  
  ftpClient.connect("127.0.0.1");
  
  ftpClient.login("f1", "123456");
  
  //String remoteFileName = "E:\\FTP\\Remote\\";
  //fos = new FileOutputStream("E:/FTP/dfff.txt");
  FTPFile[] fs = ftpClient.listFiles();
  ftpClient.setBufferSize(1024);
  // 设置文件类型(二进制)
  ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  for (int i = 0; i < fs.length; i++) {
  
  FTPFile ff = fs;
  
  FileOutputStream outputStream = new FileOutputStream("E:/FTP/"+ff.getName());
  
  //ff.getName().equals(fileName)
  if (true) {
  
  //String filename = fileName;
  
  // 这个就就是弹出下载对话框的关键代码
  
  /*response.setHeader("Content-disposition",
  
  "attachment;filename="
  
  + URLEncoder.encode(filename, "utf-8"));*/
  // 将文件保存到输出流outputStream中
  
  ftpClient.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), outputStream);
  outputStream.flush();
  outputStream.close();
  
  }
  
  }
  // ftpClient.changeWorkingDirectory(remoteFileName);
  
  //ftpClient.retrieveFile(remoteFileName + "3333.txt", fos);
  } catch (IOException e) {
  e.printStackTrace();
  throw new RuntimeException("FTP客户端出错!", e);
  } finally {
  IOUtils.closeQuietly(fos);
  try {
  ftpClient.disconnect();
  } catch (IOException e) {
  e.printStackTrace();
  throw new RuntimeException("关闭FTP连接发生异常!", e);
  }
  }
  }
  
  public static void testDownload() {
  FTPClient ftpClient = new FTPClient();
  FileOutputStream fos = null;
  
  try {
  
  ftpClient.connect("127.0.0.1");
  //登錄之後就是給用戶配置的默认地址
  //对于window,假定配置了E://FTP,
  //登录时服务端看到的登录的起始目录是/
  ftpClient.login("f1", "123456");
  
  String remoteFileName = "fff.txt";
  fos = new FileOutputStream("E:/FTP/dfff.txt");
  ftpClient.setBufferSize(1024);
  // 设置文件类型(二进制)
  ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  
  ftpClient.retrieveFile(remoteFileName, fos);
  
  } catch (IOException e) {
  e.printStackTrace();
  throw new RuntimeException("FTP客户端出错!", e);
  } finally {
  IOUtils.closeQuietly(fos);
  try {
  ftpClient.disconnect();
  } catch (IOException e) {
  e.printStackTrace();
  throw new RuntimeException("关闭FTP连接发生异常!", e);
  }
  }
  }
  }
  
  
  
  package com.teradata.util;
  
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.util.Iterator;
  import java.util.Properties;
  import java.util.Vector;
  
  import com.jcraft.jsch.Channel;
  import com.jcraft.jsch.ChannelSftp;
  import com.jcraft.jsch.JSch;
  import com.jcraft.jsch.Session;
  import com.jcraft.jsch.SftpATTRS;
  import com.jcraft.jsch.SftpException;
  import com.jcraft.jsch.ChannelSftp.LsEntry;
  
  public class BSFTPTest {
  
  private String host;
  private String username;
  private String password;
  private int port = 22;
  private ChannelSftp sftp = null;
  private Session sshSession = null;
  
  public BSFTPTest() {
  }
  
  public BSFTPTest(String host, String username, String password, int port) {
  this.host = host;
  this.username = username;
  this.password = password;
  this.port = port;
  }
  
  public BSFTPTest(String host, String username, String password) {
  this.host = host;
  this.username = username;
  this.password = password;
  }
  
  /**
  * connect server via sftp
  */
  public boolean connect() {
  try {
  
  JSch jsch = new JSch();
  sshSession = jsch.getSession(username, host, port);
  System.out.println("Session created.");
  sshSession.setPassword(password);
  Properties sshConfig = new Properties();
  sshConfig.put("StrictHostKeyChecking", "no");
  sshSession.setConfig(sshConfig);
  sshSession.setPort(21);
  sshSession.connect();
  System.out.println("Session connected.");
  System.out.println("Opening Channel.");
  Channel channel = sshSession.openChannel("sftp");
  channel.connect();
  sftp = (ChannelSftp) channel;
  System.out.println("Connected to " + host + ".");
  return true;
  } catch (Exception e) {
  e.printStackTrace();
  return false;
  }
  }
  
  /**
  * 关闭资源
  */
  public void disconnect() {
  if (this.sftp != null) {
  if (this.sftp.isConnected()) {
  this.sftp.disconnect();
  System.out.println("sftp is closed already");
  }
  }
  
  if (this.sshSession != null) {
  if (this.sshSession.isConnected()) {
  this.sshSession.disconnect();
  System.out.println("sshSession is closed already");
  }
  
  }
  
  }
  
  /**
  * 批量下载文件
  * 
  * @param remotPath
  *            远程下载目录(以路径符号结束)
  * @param localPath
  *            本地保存目录(以路径符号结束)
  * @param fileFormat
  *            下载文件格式(以特定字符开头,为空不做检验)
  * @param del
  *            下载后是否删除sftp文件
  * @return
  */
  public boolean batchDownLoadFile(String remotPath, String localPath,
  String fileFormat, boolean del) {
  
  try {
  sftp.cd(remotPath);
  //Vector v = listFiles(remotPath);
  Vector v = sftp.ls(remotPath);
  if (v.size() > 0) {
  
  Iterator it = v.iterator();
  while (it.hasNext()) {
  LsEntry entry = (LsEntry) it.next();
  String filename = entry.getFilename();
  SftpATTRS attrs = entry.getAttrs();
  if (!attrs.isDir()) {
  if (fileFormat != null && !"".equals(fileFormat.trim())) {
  if (filename.startsWith(fileFormat)) {
  if (this.downloadFile(remotPath, filename,
  localPath, filename) && del) {
  deleteSFTP(remotPath, filename);
  }
  }
  } else {
  if (this.downloadFile(remotPath, filename,
  localPath, filename) && del) {
  deleteSFTP(remotPath, filename);
  }
  }
  }
  }
  }
  } catch (SftpException e) {
  e.printStackTrace();
  } finally {
  this.disconnect();
  }
  return false;
  }
  
  /**
  * 下载单个文件
  * 
  * @param remotPath
  *            远程下载目录(以路径符号结束)
  * @param remoteFileName
  *            下载文件名
  * @param localPath
  *            本地保存目录(以路径符号结束)
  * @param localFileName
  *            保存文件名
  * @return
  */
  public boolean downloadFile(String remotePath, String remoteFileName,
  String localPath, String localFileName) {
  try {
  File file = new File(localPath + localFileName);
  mkdirs(localPath + localFileName);
  sftp.get(remoteFileName, new FileOutputStream(file));
  return true;
  } catch (FileNotFoundException e) {
  e.printStackTrace();
  } catch (SftpException e) {
  e.printStackTrace();
  }
  
  return false;
  }
  
  /**
  * 上传单个文件
  * 
  * @param remotePath
  *            远程保存目录
  * @param remoteFileName
  *            保存文件名
  * @param localPath
  *            本地上传目录(以路径符号结束)
  * @param localFileName
  *            上传的文件名
  * @return
  */
  public boolean uploadFile(String remotePath, String remoteFileName,
  String localPath, String localFileName) {
  FileInputStream in = null;
  try {
  createDir(remotePath);
  File file = new File(localPath + localFileName);
  in = new FileInputStream(file);
  sftp.put(in, remoteFileName);
  return true;
  } catch (FileNotFoundException e) {
  e.printStackTrace();
  } catch (SftpException e) {
  e.printStackTrace();
  } finally {
  if (in != null) {
  try {
  in.close();
  } catch (IOException e) {
  e.printStackTrace();
  }
  }
  }
  return false;
  }
  
  /**
  * 批量上传文件
  * 
  * @param remotePath
  *            远程保存目录
  * @param localPath
  *            本地上传目录(以路径符号结束)
  * @param del
  *            上传后是否删除本地文件
  * @return
  */
  public boolean bacthUploadFile(String remotePath, String localPath,
  boolean del) {
  try {
  connect();
  File file = new File(localPath);
  File[] files = file.listFiles();
  for (int i = 0; i < files.length; i++) {
  if (files.isFile()
  && files.getName().indexOf("bak") == -1) {
  if (this.uploadFile(remotePath, files.getName(),
  localPath, files.getName()) && del) {
  deleteFile(localPath + files.getName());
  
  }
  }
  }
  return true;
  } catch (Exception e) {
  e.printStackTrace();
  } finally {
  this.disconnect();
  }
  return false;
  
  }
  
  /**
  * 删除本地文件
  * 
  * @param filePath
  * @return
  */
  public boolean deleteFile(String filePath) {
  File file = new File(filePath);
  if (!file.exists()) {
  return false;
  }
  
  if (!file.isFile()) {
  return false;
  }
  
  return file.delete();
  }
  
  /**
  * 创建目录
  * 
  * @param createpath
  * @return
  */
  public boolean createDir(String createpath) {
  try {
  if (isDirExist(createpath)) {
  this.sftp.cd(createpath);
  return true;
  }
  String pathArry[] = createpath.split("/");
  StringBuffer filePath = new StringBuffer("/");
  for (String path : pathArry) {
  if (path.equals("")) {
  continue;
  }
  filePath.append(path + "/");
  if (isDirExist(filePath.toString())) {
  sftp.cd(filePath.toString());
  } else {
  // 建立目录
  sftp.mkdir(filePath.toString());
  // 进入并设置为当前目录
  sftp.cd(filePath.toString());
  }
  
  }
  this.sftp.cd(createpath);
  return true;
  } catch (SftpException e) {
  e.printStackTrace();
  }
  return false;
  }
  
  /**
  * 判断目录是否存在
  * 
  * @param directory
  * @return
  */
  public boolean isDirExist(String directory) {
  boolean isDirExistFlag = false;
  try {
  SftpATTRS sftpATTRS = sftp.lstat(directory);
  isDirExistFlag = true;
  return sftpATTRS.isDir();
  } catch (Exception e) {
  if (e.getMessage().toLowerCase().equals("no such file")) {
  isDirExistFlag = false;
  }
  }
  return isDirExistFlag;
  }
  
  /**
  * 删除stfp文件
  * 
  * @param directory
  *            要删除文件所在目录
  * @param deleteFile
  *            要删除的文件
  * @param sftp
  */
  public void deleteSFTP(String directory, String deleteFile) {
  try {
  sftp.cd(directory);
  sftp.rm(deleteFile);
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
  
  /**
  * 如果目录不存在就创建目录
  * 
  * @param path
  */
  public void mkdirs(String path) {
  File f = new File(path);
  String fs = f.getParent();
  f = new File(fs);
  
  if (!f.exists()) {
  f.mkdirs();
  }
  }
  
  /**
  * 列出目录下的文件
  * 
  * @param directory
  *            要列出的目录
  * @param sftp
  * @return
  * @throws SftpException
  */
  public Vector listFiles(String directory) throws SftpException {
  return sftp.ls(directory);
  }
  
  public String getHost() {
  return host;
  }
  
  public void setHost(String host) {
  this.host = host;
  }
  
  public String getUsername() {
  return username;
  }
  
  public void setUsername(String username) {
  this.username = username;
  }
  
  public String getPassword() {
  return password;
  }
  
  public void setPassword(String password) {
  this.password = password;
  }
  
  public int getPort() {
  return port;
  }
  
  public void setPort(int port) {
  this.port = port;
  }
  
  public ChannelSftp getSftp() {
  return sftp;
  }
  
  public void setSftp(ChannelSftp sftp) {
  this.sftp = sftp;
  }
  
  public static void main(String[] args) {
  
  String hosts =  Constant.getStPara("hosts");
  String user = Constant.getStPara("user");
  String pwd = Constant.getStPara("pwd");
  
  BSFTPTest ftp = new BSFTPTest(hosts,user,pwd);
  String localPath = Constant.getStPara("localPath");
  String remotePath = Constant.getStPara("remotePath");
  
  ftp.connect();
  ftp.batchDownLoadFile(remotePath, localPath, null, false);
  ftp.disconnect();
  
  System.exit(0);
  }
  
  }
  
  
  
  
  package com.teradata.util;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.util.Properties;
  import java.util.Vector;
  
  import com.jcraft.jsch.Channel;
  import com.jcraft.jsch.ChannelSftp;
  import com.jcraft.jsch.JSch;
  import com.jcraft.jsch.JSchException;
  import com.jcraft.jsch.Session;
  import com.jcraft.jsch.SftpException;
  
  /**
  */
  public class SFtpTest {
  
  /**
  * 连接sftp服务器
  * 
  * @param host
  *            主机
  * @param port
  *            端口
  * @param username
  *            用户名
  * @param password
  *            密码
  * @return
  */
  public ChannelSftp connect(String host, int port, String username,
  String password) {
  ChannelSftp sftp = null;
  try {
  JSch jsch = new JSch();
  Session sshSession = jsch.getSession(username, host, port);
  System.out.println("Session created.");
  sshSession.setPassword(password);
  Properties sshConfig = new Properties();
  
  sshConfig.put("StrictHostKeyChecking", "no");
  // sshConfig.put("PasswordAuthentication", "no");
  
  sshSession.setConfig(sshConfig);
  sshSession.connect();
  System.out.println("Session connected.");
  System.out.println("Opening Channel.");
  Channel channel = sshSession.openChannel("sftp");
  channel.connect();
  sftp = (ChannelSftp) channel;
  System.out.println("Connected to " + host + ".");
  } catch (Exception e) {
  e.printStackTrace();
  }
  return sftp;
  }
  
  /**
  * 上传文件
  * 
  * @param directory
  *            上传的目录
  * @param uploadFile
  *            要上传的文件
  * @param sftp
  */
  public void upload(String directory, String uploadFile, ChannelSftp sftp) {
  try {
  sftp.cd(directory);
  File file = new File(uploadFile);
  sftp.put(new FileInputStream(file), file.getName());
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
  
  /**
  * 下载文件
  * 
  * @param directory
  *            下载目录
  * @param downloadFile
  *            下载的文件
  * @param saveFile
  *            存在本地的路径
  * @param sftp
  */
  public void download(String directory, String downloadFile,
  String saveFile, ChannelSftp sftp) {
  try {
  sftp.cd(directory);
  File file = new File(saveFile);
  sftp.get(downloadFile, new FileOutputStream(file));
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
  
  /**
  * 删除文件
  * 
  * @param directory
  *            要删除文件所在目录
  * @param deleteFile
  *            要删除的文件
  * @param sftp
  */
  public void delete(String directory, String deleteFile, ChannelSftp sftp) {
  try {
  sftp.cd(directory);
  sftp.rm(deleteFile);
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
  
  /**
  * 列出目录下的文件
  * 
  * @param directory
  *            要列出的目录
  * @param sftp
  * @return
  * @throws SftpException
  */
  public Vector listFiles(String directory, ChannelSftp sftp)
  throws SftpException {
  return sftp.ls(directory);
  }
  
  public static void main(String[] args) throws JSchException {
  SFtpTest sf = new SFtpTest();
  String host = "192.168.1.104";
  int port = 22;
  String username = "root";
  String password = "root";
  String directory = "/root/";
  String downloadFile = "tdebg.jpg";
  String saveFile = "E:/FTP/jjj.jpg";
  ChannelSftp sftp = sf.connect(host, port, username, password);
  // sf.upload(directory, uploadFile, sftp);
  try {
  sftp.cd(directory);
  File file = new File(saveFile);
  sftp.get(downloadFile, new FileOutputStream(file));
  System.out.println("download file success, file:" + downloadFile);
  } catch (SftpException e) {
  e.printStackTrace();
  }catch (FileNotFoundException e) {
  e.printStackTrace();
  } finally {
  // 如果没有sesstion的disconnect,程序不会退出
  sftp.getSession().disconnect();
  sftp.disconnect();
  sftp.exit();
  }
  }
  }
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-227329-1-1.html 上篇帖子: ftp服务 下篇帖子: ftp 连接
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表