Using SSH to implement server file upload and download _java

Source: Internet
Author: User
Tags getmessage mkdir zip stringbuffer

Upload and download server files via SSH

It's written in front of you.

Previously recorded a use of Apache FTP open source components to implement server file upload download method, but later found that the deletion of some permissions problems, resulting in the server can not delete files. Although it is OK to use FileZilla server to set read and write permissions on Windows, it is still a bit of a bad idea on the server side.

Because they need to implement the resource management function, in addition to the FASTDFS storage of single files, some specific resources of storage or intend to temporarily store the server, the project team colleagues said that the following will not be dedicated to the server on the FTP service, and then changed to the SFTP way to operate.

How do you use this thing?

First to download the Jsch jar package, the address is: http://www.jcraft.com/jsch/. It is also clearly written on the website: Jsch is a pure Java implementation of SSH2. This is a pure Java implementation of SSH2. Using the IP and port, enter the username password to be used normally, and the secure CRT is used in the same way. So how do you use this useful tool?

In fact, it doesn't matter, the official also gave an example, Links: Http://www.jcraft.com/jsch/examples/Shell.java, take a look at it:

/*-*-MODE:JAVA; C-basic-offset:2;
 Indent-tabs-mode:nil-*-*//** * This program enables you to connect to sshd server and get the shell prompt. * $ classpath=.:.. /build Javac Shell.java * $ classpath=.:.. 
 /build Java Shell * You'll be asked username, hostname and passwd. * If Everything works fine, you'll get the shell prompt.
 Output may * is ugly because of lacks of terminal-emulation, but you can issue commands.
* * */import com.jcraft.jsch.*;
Import java.awt.*;

Import javax.swing.*;

  public class shell{public static void Main (string[] arg) {try{Jsch jsch=new Jsch ();

  Jsch.setknownhosts ("/home/foo/.ssh/known_hosts");
  String Host=null;
  if (arg.length>0) {host=arg[0];
           } else{Host=joptionpane.showinputdialog ("Enter username@hostname", System.getproperty ("User.Name") + 
  "@localhost");
  String user=host.substring (0, Host.indexof (' @ '));

  Host=host.substring (Host.indexof (' @ ') +1); Session session=jsch.getsession (User, HoSt, 22);
  String passwd = joptionpane.showinputdialog ("Enter password");

  Session.setpassword (passwd); UserInfo UI = New Myuserinfo () {public void ShowMessage (String message) {Joptionpane.showmessagedialog (NULL, message)
  ;
   public boolean Promptyesno (String message) {object[] options={"yes", "no"}; int Foo=joptionpane.showoptiondialog (NULL, message, "Warning", Joptionpane.default_o
   Ption, Joptionpane.warning_message, NULL, Options, options[0]);
  return foo==0;  }//If password is not given before the invocation of Session#connect (),//implement also following, methods,//* Userinfo#getpassword (),//* Userinfo#promptpassword (String message) and//* Uikeyboardinteractive#promptkeyboardint

  Eractive ()};

  Session.setuserinfo (UI); It must not being recommended, but if you want to skip Host-key check,//Invoke following,//Session.setconfig ("Stri

  Cthostkeychecking "," no "); //Session.connect (); Session.connect (30000);

  Making a connection with timeout.

  Channel Channel=session.openchannel ("shell");
  Enable agent-forwarding.

  ((Channelshell) channel). Setagentforwarding (True);
  Channel.setinputstream (system.in);
  /*//A hack for MS-DOS prompt on Windows. 
   Channel.setinputstream (New FilterInputStream (system.in) {public int read (byte[] b, int off, int len) throws ioexception{
   Return In.read (b, off, (Len>1024?1024:len));
  }
  });

  * * Channel.setoutputstream (System.out);
  *///Choose the Pty-type "vt102".
  ((Channelshell) channel). Setptytype ("vt102");
  */*///SET environment variable "LANG" as "JA_JP.EUCJP".
  ((Channelshell) channel). SETENV ("LANG", "JA_JP.EUCJP");
  * *//channel.connect ();
 Channel.connect (3*1000);
 catch (Exception e) {System.out.println (e); } public static abstract class Myuserinfo implements UserInfo, uikeyboardinteractive{public String Getpasswo
 RD () {return null;} PublicBoolean Promptyesno (String str) {return false;}
 Public String Getpassphrase () {return null;}
 public boolean promptpassphrase (String message) {return false;}
 public boolean Promptpassword (String message) {return false;} public void ShowMessage (String message) {} public string[] promptkeyboardinteractive (string destination, Stri
 ng name, String instruction, string[] prompt, boolean[] echo {return null;

 }
 }
}

In this code, we can basically see what is needed, first we want to create user information, this is mainly for the authentication of the time used, as long as the implementation of UserInfo, uikeyboardinteractive the two interfaces, and then by creating session sessions, The userinfo is set in, and the final connection can be made.

Package File Upload Download

The above is the basic use of Jsch, that is, some basic routines. Below we have to encapsulate their own to use the function to achieve file upload and download a series of operations.

First, you also create a userinfo:

public class Myuserinfo implements UserInfo, uikeyboardinteractive{public
 String GetPassword () {return null;}
 public boolean Promptyesno (String str) {return
  true;
 }
 Public String Getpassphrase () {return null;}
 public boolean promptpassphrase (String message) {return true;}
 public boolean Promptpassword (String message) {return
  true;
 }
 public void ShowMessage (String message) {
 }
 @Override public
 string[] Promptkeyboardinteractive ( String arg0, String arg1,
   string arg2, string[] arg3, boolean[] arg4) {return
  null;
 }
}

Here is the implementation class:

Package com.tfxiaozi.common.utils;
Import Java.io.InputStream;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;

Import Java.util.Vector;

Import Org.apache.log4j.Logger;
Import Com.jcraft.jsch.Channel;
Import com.jcraft.jsch.ChannelExec;
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;
Import Com.jcraft.jsch.SftpProgressMonitor;
 /** * SSH Utils * @author tfxiaozi * */public class SSH {Logger Logger = Logger.getlogger (This.getclass ());
 Private String host = "";
 Private String user = ""; 
 private int port = 22;
 Private String Password = "";
 private static final String PROTOCOL = "SFTP";
 Jsch Jsch = new Jsch ();
 Private session session;
 Private Channel Channel;

 Private Channelsftp sftp;
 Public String GetHost () {return host;
 public void Sethost (String host) {this.host = host;
  Public String GetUser () {return user;
 public void SetUser (String user) {this.user = user;
  Public ssh () {} public ssh (string host, int port, string user, string password) {this.host = host;
  This.user = user;
  This.password = password;
 This.port = port; /** * Connect SSH * @throws jschexception */public void Connect () throws Jschexception {if (session = NULL
   {session = Jsch.getsession (user, host, port);
   Myuserinfo UI = new Myuserinfo ();
   Session.setuserinfo (UI);
   Session.setpassword (password);
   Session.connect ();
   Channel = Session.openchannel (PROTOCOL);
   Channel.connect ();
  SFTP = (channelsftp) channel;
   }/** * Disconnect ssh */public void disconnect () {if (session!= null) {session.disconnect ();
  session = NULL; }/** * Upload * @param localfilename * @param remotefilename * @return * * Public boolean upload (String lo
  Calfilename, String Remotefilename) throws exception{Boolean bsucc = false; try {SFTPPROgressmonitor monitor=new myprogressmonitor ();
   int mode=channelsftp.overwrite; 
   Sftp.put (LocalFilename, remotefilename, monitor, mode);
  BSUCC = true;
  catch (Exception e) {logger.error (e);
   finally {if (null!= channel) {channel.disconnect ();
 } return BSUCC; /** * Delete file * @param directory * @param fileName * @return/public boolean detelefile (String Direct
  Ory, String fileName) {Boolean flag = false;
   try {sftp.cd (directory);
   SFTP.RM (FileName);
  Flag = true;
   catch (Sftpexception e) {flag = false;
  Logger.error (e);
 return flag; /** * Delete directory * @param directory dir to is delete * @param sure be sure to delete * * @return/Pub
  Lic string Deletedir (String directory, boolean sure) {string command = "RM-RF" + directory;
  String result = execcommand (command, True);
 return result; }/** * Compress the files and Sub-dir of directory into a zip named Compressname * @paraM directory The content directory to being compress * @param compressname the name in directory over it is compressed *
  @throws sftpexception * @usage ssh.compressdir ("/home/tfxiaozi/webapp", "Test.zip"); */public void Compressdir (string directory, String compressname) throws sftpexception {string command = "CD" + Direct
  Ory + "\nzip-r" + Compressname + "./" + compressname.substring (0, Compressname.lastindexof ("."));
 ExecCommand (command, True); /** * Download * @param localfilename * @param remotefilename * @return * * Public boolean download (String
  LocalFilename, String remotefilename) {Boolean bsucc = false;
  Channel Channel = null;
   try {sftpprogressmonitor monitor = new Myprogressmonitor (); 
   Sftp.get (Remotefilename, LocalFilename, Monitor, channelsftp.overwrite);
  BSUCC = true;
  catch (Exception e) {logger.error (e);
   finally {if (null!= channel) {channel.disconnect ();
 } return BSUCC; }/** * Execute command * @param command * @param flag * @return/public string execcommand (String command, Boolean flag) {Channe
  L channel = null;
  InputStream in = null;
  StringBuffer sb = new StringBuffer ("");
   try {channel = Session.openchannel ("exec");
   System.out.println ("command:" + command);
   ((channelexec) channel). SetCommand ("Export term=ansi &&" + command);
   ((channelexec) channel). Seterrstream (System.err);
   in = Channel.getinputstream ();
   Channel.connect ();
    if (flag) {byte[] tmp = new byte[10240];
      while (true) {while (in.available () >0) {int i = in.read (tmp, 0, 10240);
      if (I < 0) {break;
     } sb.append (New String (TMP, 0, i));
     } if (channel.isclosed ()) {break;
  }} in.close ();
  catch (Exception e) {logger.error (e);
   finally {if (channel!= null) {channel.disconnect ();
 } return sb.tostring (); /** * Get CPU Info * @return/public string[]Getcpuinfo () {Channel Channel = null;
  InputStream in = null;
  StringBuffer sb = new StringBuffer ("");
   try {channel = Session.openchannel ("exec");
   ((channelexec) channel). SetCommand ("Export term=ansi && top-bn 1");//ansi must add in = Channel.getinputstream ();
   ((channelexec) channel). Seterrstream (System.err);
   Channel.connect ();
   byte[] tmp = new byte[10240];
     while (true) {while (in.available () >0) {int i = in.read (tmp, 0, 10240);
     if (I < 0) {break;
    } sb.append (New String (TMP, 0, i));
    } if (channel.isclosed ()) {break;
  catch (Exception e) {logger.error (e);
   finally {if (channel!= null) {channel.disconnect ();
  } String buf = Sb.tostring ();
  if (Buf.indexof ("swap")!=-1) {buf = buf.substring (0, Buf.indexof ("swap"));
  } if (Buf.indexof ("CPU")!=-1) {buf = buf.substring (Buf.indexof ("CPU"), Buf.length ());
  } buf.replaceall ("", " "); return Buf.split ("\\ n "); /** * Get Hard disk Info * @return/public String Getharddiskinfo () throws exception{Channel Channel = nul
  L
  InputStream in = null;
  StringBuffer sb = new StringBuffer ("");
   try {channel = Session.openchannel ("exec");
   ((channelexec) channel). SetCommand ("Df-lh");
   in = Channel.getinputstream ();
   ((channelexec) channel). Seterrstream (System.err);

   Channel.connect ();
   byte[] tmp = new byte[10240];
     while (true) {while (in.available () >0) {int i = in.read (tmp, 0, 10240);
     if (I < 0) {break;
    } sb.append (New String (TMP, 0, i));
    } if (channel.isclosed ()) {break;
  The catch (Exception e) {throw new RuntimeException (e);
   finally {if (channel!= null) {channel.disconnect ();
  } String buf = Sb.tostring ();
  String[] Info = buf.split ("\ n");
   if (Info.length > 2) {//first line:filesystem Size Used avail use% mounted on String tmp = ""; for (int i=1; i< info.length; i++) {tmp = Info[i];
    string[] Tmparr = tmp.split ("%");
     if (Tmparr[1].trim (). Equals ("/")) {Boolean flag = true;
      while (flag) {TMP = Tmp.replaceall ("", "");
      if (Tmp.indexof ("") = = 1) {flag = false;
     } string[] result = Tmp.split (""); if (Result!= null && result.length = = 6) {buf = Result[1] + "total," + result[2] + "used," + result[3]
      + "free";
     Break
     else {buf = "";
  }}} else {buf = "";
 return buf; /** * Returns the number of free bytes * @return * @throws Exception/public double Getfreedisk () throws Exception {String Hardd
  Iskinfo = Getharddiskinfo ();
   if (Harddiskinfo = null | | harddiskinfo.equals ("")) {Logger.error ("Get free harddisk spaces failed ...");
  return-1;
  } string[] DiskInfo = Harddiskinfo.replace ("", ""). Split (",");
   if (DiskInfo = null | | diskinfo.length = = 0) {logger.error ("Get free disk info failed ..."); Return-1;
  } String free = diskinfo[2];
  Free = free.substring (0, Free.indexof ("free"));
  System.out.println ("Free spaces:" + free);
  String unit = free.substring (Free.length ()-1);
  SYSTEM.OUT.PRINTLN ("Unit:" + unit);
  String freeSpace = free.substring (0, Free.length ()-1);
  Double freespacel = double.parsedouble (freeSpace);
  System.out.println ("Free spacel:" + freespacel);
  if (Unit.equals ("K")) {return freespacel*1024;
  }else if (unit.equals ("M")) {return freespacel*1024*1024;
  else if (unit.equals ("G")) {return freespacel*1024*1024*1024;
  else if (unit.equals ("T")) {return freespacel*1024*1024*1024*1024;
  else if (unit.equals ("P")) {return freespacel*1024*1024*1024*1024*1024;
 return 0; /** * Get all subdirectories and files in the specified directory * @param directory * @return * @throws Exception/@SuppressWarnings ("Rawtypes") p
  Ublic list<string> listfiles (String directory) throws Exception {Vector filelist = null; list<string> filenamelist = new ARRAylist<string> ();
  FileList = sftp.ls (directory);
  Iterator it = Filelist.iterator ();
   while (It.hasnext ()) {String FileName = ((channelsftp.lsentry) It.next ()). GetFileName (); if (Filename.startswith (".") | | filename.startswith ("..")
   {continue;
  } filenamelist.add (FileName);
 return filenamelist;
  public boolean mkdir (String path) {Boolean flag = false;
   try {sftp.mkdir (path);
  Flag = true;
  catch (Sftpexception e) {flag = false;
 return flag;

 }
}

Test

public static void Main (string[] arg) throws exception{ssh ssh = new ssh ("10.10.10.83",
  try {ssh.connect ();
  catch (Jschexception e) {e.printstacktrace ();
  }/*string RemotePath = "/home/tfxiaozi/" + "webapp/";
  try {ssh.listfiles (RemotePath);
  catch (Exception e) {ssh.mkdir (RemotePath);
  }*//*boolean B = ssh.upload ("D:/test.zip", "webapp/");
  System.out.println (b); *///string []BUF = Ssh.getcpuinfo ();
  SYSTEM.OUT.PRINTLN ("CPU:" + buf[0]);
  System.out.println ("Memo:" + buf[1]);
  System.out.println (Ssh.getharddiskinfo (). Replace ("", ""));


  System.out.println (Ssh.getfreedisk ());
  /*list<string> List = ssh.listfiles ("Webapp/test");
  for (String s:list) {System.out.println (s);
  }*//*boolean B = ssh.detelefile ("WebApp", "Test.zip");
   System.out.println (b); *//*try {String s = Ssh.execcommand ("Ls-l/home/tfxiaozi/webapp1/test", true);
  System.out.println (s);
catch (Exception e) {   System.out.println (E.getmessage ());

  }*///ssh.sftp.setfilenameencoding ("UTF-8");
   /*try {String ss = Ssh.execcommand ("unzip/home/tfxiaozi/webapp1/test.zip-d/home/tfxiaozi/webapp1/", true);
  SYSTEM.OUT.PRINTLN (ss);
  catch (Exception e) {System.out.println (E.getmessage ());
  }*//*string Path = "/home/tfxiaozi/webapp1/test.zip";
   try {list<string> List = ssh.listfiles (path);
   for (String s:list) {System.out.println (s);
  } System.out.println ("OK");
  catch (Exception e) {System.out.println ("Extract failed ...");
  }*//*string command = "rm-rf/home/tfxiaozi/webapp1/" + "Chinese-ink Sinology";
  String sss = Ssh.execcommand (command, True);
  SYSTEM.OUT.PRINTLN (SSS), * */*string Findcommand = "find/home/tfxiaozi/webapp1/'-name '";
  String result = Ssh.execcommand (Findcommand, true);
  SYSTEM.OUT.PRINTLN (result); * */*string Path = "";
   Ssh.listfiles (RemotePath); * * Ssh.deletedir ("/home/tfxiaozi/webapp1", true);*//below This will extract to WebApp1 directory, webapp1/test/xxx//ssh.execcommand ("unzip/home/tfxiaozi/webapp1/test.zip-d/home/tfxiaozi/
  WebApp1 ", true); This will be extracted to the/webapp1/test directory, also webapp1/test/test/xxx//ssh.execcommand ("unzip/home/tfxiaozi/webapp1/test.zip-d/

  Home/tfxiaozi/webapp1 ", true);

  Ssh.compressdir ("/home/tfxiaozi/webapp1", "Test.zip");
  SSH.SFTP.CD ("/home/tfxiaozi/webapp1");

  Ssh.compressdir ("/home/tfxiaozi/webapp1", "Test.zip");
  /*boolean B = ssh.download ("D:/temp/test.zip", "Webapp/test.zip");
  System.out.println (b); *///ssh.getharddiskinfo ();
  System.out.println (Ssh.getfreedisk ());
 Ssh.disconnect ();

 }

The above is the direct use of Linux to operate, but it should be noted that for Chinese documents, in the decompression, when the incoming will be garbled, need to add parameters, such as Unzip-o cp936 test.zip-d/home/tfxiaozi/test.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.