Téléchargement des fichiers du serveur et téléchargement via SSH
Mots écrits à l'avant
J'ai précédemment enregistré une méthode pour télécharger et télécharger des fichiers de serveur à l'aide du composant Open Source FTP d'Apache, mais plus tard, j'ai constaté qu'il y aura des problèmes d'autorisation lors de la suppression, ce qui entraînera l'incapacité de supprimer des fichiers sur le serveur. Bien qu'il n'y ait pas de problème après la définition des autorisations de lecture et d'écriture à l'aide du serveur Filezilla sur Windows, il est toujours un peu difficile à utiliser du côté du serveur.
Parce que j'ai besoin d'implémenter les fonctions de gestion des ressources, en plus du stockage FastDFS de fichiers uniques, un certain stockage de ressources spécifiques est toujours prévu pour être temporairement stocké sur le serveur. Les collègues de l'équipe du projet ont déclaré qu'ils n'ouvriraient pas les services FTP spécifiquement sur le serveur plus tard, ils ont donc changé pour SFTP pour fonctionner.
Comment utiliser cette chose
Tout d'abord, vous devez télécharger le package JAR JSCH, l'adresse est: http://www.jcraft.com/jsch/. Le site Web écrit également très clairement: JSCH est une pure implémentation Java de SSH2. Il s'agit d'une pure implémentation Java de SSH2. Utilisez IP et Port, entrez le nom d'utilisateur et le mot de passe et vous pouvez l'utiliser normalement, ce qui est le même que la méthode d'utilisation de Secure CRT. Alors, comment utilisez-vous cet outil utile?
En fait, peu importe si vous ne pouvez pas l'écrire. Le responsable a également donné un exemple. Le lien est: http://www.jcraft.com/jsch/examples/shell.java. Jetons un coup d'œil:
/ * - * - mode: java; C-Basic-Offset: 2; Mode de tabs de fond: nil - * - * // ** * Ce programme vous permet de vous connecter au serveur SSHD et d'obtenir l'invite de shell. * $ Classpath =.: ../ construire javac shell.java * $ classpath =.: ../ construire java shell * on vous demandera le nom d'utilisateur, le nom d'hôte et le passwd. * Si tout fonctionne bien, vous obtiendrez l'invite du shell. La sortie peut * être laide en raison du manque d'émulation des terminaux, mais vous pouvez émettre des commandes. * 11 //jsch.setknownhosts("/home/foo/.ssh/known_hosts "); String host = null; if (arg.length> 0) {host = arg [0]; } else {host = jOptionPane.showInputDialog ("Entrez UserName @ hostname", System.getProperty ("user.name") + "@localhost"); } String user = host.substring (0, host.indexof ('@')); host = host.substring (host.indexof ('@') + 1); Session session = jsch.getSession (utilisateur, hôte, 22); String Passwd = jOptionPane.ShowInputDialog ("Entrez le mot de passe"); session.setpassword (passwd); UserInfo ui = new myUserInfo () {public void showMessage (message de chaîne) {joptionPane.showMessageDialog (null, message); } public boolean promptyesNo (message de chaîne) {objet [] options = {"Oui", "non"}; int foo = joptionpane.showoptionDialog (null, message, "avertissement", joptionpane.default_option, joptionpane.warning_message, null, options, options [0]); return foo == 0; } // Si le mot de passe n'est pas donné avant l'invocation de la session # connect (), // implémenter également des méthodes suivantes, // * userInfo # getPassword (), // * userInfo # promptPassword (message de chaîne) et // * uikeyboardinteractive # promptKeyboardInteractive ()}; session.setUserInfo (UI); // il ne faut pas recommander, mais si vous souhaitez sauter la vérification de la clé hôte, // invoquer la suite, // session.setConfig ("stricThostKeyChecking", "non"); //Session.Connect (); session.connect (30000); // établissant une connexion avec le délai d'attente. Channel Channel = Session.Opennannel ("Shell"); // Activer l'agent à l'agent. //((CHANNELSHELL)CHANNEL).SetAgentForwarding(True); Channel.SetInputStream (System.in); / * // Une invite de piratage pour MS-DOS sur Windows. channel.setInputStream (new FilterInputStream (System.in) {public int read (byte [] b, int off, int len) lève ioException {return in.read (b, off, (len> 1024? 1024: len));}}); * / canal.setOutputStream (System.out); / * // Choisissez le "VT102" de type pty. ((ChannelShell) canal) .setptyType ("VT102"); * / / * // Définir la variable d'environnement "Lang" comme "ja_jp.eucjp". ((ChannelShell) canal) .setenv ("lang", "ja_jp.eucjp"); * / //channel.connect (); canal.connect (3 * 1000); } catch (exception e) {System.out.println (e); }} public static abstract class MyUserInfo implémente userInfo, uikeyboardinteractive {public String getPassword () {return null; } public boolean promptyesNo (String str) {return false; } public String getPassPhrase () {return null; } public boolean insidepassPhrase (String Message) {return false; } public boolean promptPassword (message de chaîne) {return false; } public void showMessage (Message de chaîne) {} public String [] insidekeyboardInterActive (String Destination, String Name, String Instruction, String [] invite, boolean [] echo) {return null; }}}Dans ce code, nous pouvons essentiellement voir ce dont nous avons besoin. Tout d'abord, nous devons créer des informations utilisateur. Ceci est principalement utilisé pour l'authentification. Implémentez simplement les deux interfaces de UserInfo et UikeyboardInteractive. Ensuite, en créant une session de session, définissez UserInfo et enfin se connecter.
Téléchargement et téléchargement de fichiers encapsulés
Ce qui précède est la méthode d'utilisation de base de JSCH, c'est-à-dire certaines routines de base. Saisissons les fonctions que nous souhaitons utiliser, implémentons une série d'opérations telles que le téléchargement et le téléchargement de fichiers.
Créez d'abord un userInfo:
classe publique MyUserInfo implémente userInfo, uikeyboardinteractive {public String getPassword () {return null; } public boolean promptyesNo (String str) {return true; } public String getPassPhrase () {return null; } public boolean insidepassPhrase (String Message) {return true; } public boolean promptPassword (message de chaîne) {return true; } public void showMessage (Message de chaîne) {} @Override public String [] insidekboardInteractive (String arg0, string arg1, string arg2, string [] arg3, boolean [] arg4) {return null; }}Voici la classe d'implémentation:
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; 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.sftpexect; com.jcraft.jsch.sftPProgressMonitor; / ** * ssh utils * @author tfxiaozi * * / public class ssh {logger logger = logger.getLogger (this.getClass ()); chaîne privée host = ""; chaîne privée User = ""; port int privé = 22; Private String Password = ""; Protocole de chaîne finale statique privée = "SFTP"; Jsch jsch = new jsch (); Session privée; canal de canal privé; Channelsftpp Private SFTP; public String gethost () {return host; } public void sethost (string host) {this.host = host; } public String getUser () {return utilisateur; } public void SetUser (String User) {this.user = user; } public ssh () {} public ssh (string host, int port, chaîne utilisateur, mot de passe de chaîne) {this.host = host; this.user = utilisateur; this.password = mot de passe; this.port = port; } / ** * connect ssh * @throws jschexception * / public void connect () lève jschexception {if (session == null) {session = jsch.getSession (utilisateur, hôte, port); MyUserInfo ui = new MyUserInfo (); session.setUserInfo (UI); session.setpassword (mot de passe); session.connect (); canal = session.Opennanal (protocole); canal.connect (); canal sftp = (canauxftp); }} / ** * Disconnect Ssh * / public void disconnect () {if (session! = null) {session.disconnect (); session = null; }} / ** * upload * @param localfilename * @param RemoteFileName * @return * / public boolean upload (String localFileName, string RemoteFileName) lève exception {boolean bsucc = false; essayez {sftPProGressMonitor Monitor = new myProgressMonitor (); int mode = canauxftp.overwrite; sftp.put (localFileName, RemoteFileName, moniteur, mode); bsucc = true; } catch (exception e) {logger.error (e); } enfin {if (null! = canal) {channel.disconnect (); }} return bsucc; } / ** * Delete Fichier * @param Directory * @param filename * @return * / public boolean DetectEFile (String Directory, String FileName) {booléen flag = false; essayez {sftp.cd (répertoire); sftp.rm (nom de fichier); Flag = true; } catch (sftPException e) {flag = false; Logger.Error (e); } drapeau de retour; }! String result = execcommand (commande, true); Résultat de retour; } / ** * Compressez les fichiers et le sous-diver du répertoire dans un zip nommé CompressName * @param Directory Le répertoire de contenu est compressé * @param compressname le nom dans le répertoire après qu'il est compressé * @throws sftpexception * @usage ssh.compressdir ("/ home / tfxiaozi / webapp", "test.zip"); * / public void compressdir (String Directory, String CompressName) lève SftPException {String Command = "CD" + Directory + "/ nzip -r" + compressname + "./" + compressName.substring (0, compressname.lastIndexof (".")); execcommand (commande, true); } / ** * Télécharger * @param localfilename * @param RemoteFileName * @return * / public boolean download (String localFilename, String RemoteFileName) {boolean bsucc = false; Canal canal = null; essayez {sftPProGressMonitor Monitor = new myProgressMonitor (); sftp.get (RemoteFileName, localFileName, moniteur, canauxftp.overwrite); bsucc = true; } catch (exception e) {logger.error (e); } enfin {if (null! = canal) {channel.disconnect (); }} return bsucc; } / ** * EXECUTER COMMAND * @param commande * @param Flag * @return * / public String execcommand (String Command, booléan Flag) {Channel Channel = NULL; InputStream dans = null; StringBuffer sb = new StringBuffer (""); essayez {canal = session.openchannel ("exec"); System.out.println ("Commande:" + Command); ((Cannexec) canal) .setCommand ("Export Term = ANSI &&" + commande); ((Cannexec) canal) .SetErterStream (System.err); dans = canal.getInputStream (); canal.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); } enfin {if (canal! = null) {channel.disconnect (); }} return sb.toString (); } / ** * Obtenez des informations CPU * @return * / public String [] getCPUInfo () {Channel Channel = Null; InputStream dans = null; StringBuffer sb = new StringBuffer (""); essayez {canal = session.openchannel ("exec"); ((Cannexec) canal) .setCommand ("Export Term = ANSI && TOP -BN 1"); // ANSI doit ajouter dans = channel.getInputStream (); ((Cannexec) canal) .SetErterStream (System.err); canal.connect (); octet [] tmp = nouveau octet [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); } enfin {if (canal! = null) {channel.disconnect (); }} Chaîne 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 () lève l'exception {canal canal Channel = null; InputStream dans = null; StringBuffer sb = new StringBuffer (""); essayez {canal = session.openchannel ("exec"); ((Cannexec) canal) .setCommand ("df -lh"); dans = canal.getInputStream (); ((Cannexec) canal) .SetErterStream (System.err); canal.connect (); octet [] tmp = nouveau octet [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) {lancez new RuntimeException (e); } enfin {if (canal! = null) {channel.disconnect (); }} Chaîne buf = sb.toString (); String [] info = buf.split ("/ n"); if (info.length> 2) {// First Line: Système de fichiers Utilisé disponible Utiliser% monté sur String tmp = ""; for (int i = 1; i <info.length; i ++) {tmp = info [i]; String [] tmparr = tmp.split ("%"); if (tmparr [1] .trim (). equals ("/")) {booléen 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] + "utilisé," + résultat [3] + "libre"; casser; } else {buf = ""; }}}} else {buf = ""; } return buf; } / ** * Renvoie le nombre d'octets gratuits * @return * @throws exception * / public double getFreedisk () lève une exception {String harddiskinfo = getharddiskinfo (); if (harddiskinfo == null || harddiskinfo.equals ("")) {logger.error ("obtenir un espace hardkisk gratuit failli ......"); retour -1; } String [] diskinfo = harddiskinfo.replace ("", "") .split (","); if (diskinfo == null || diskinfo.length == 0) {Logger.Error ("obtenir des informations sur le disque gratuites ......"); retour -1; } String free = diskinfo [2]; free = free.substring (0, free.indexof ("free")); //System.out.println("free Space: "+ gratuit); String Unit = free.substring (free.length () - 1); //System.out.println("Unit: "+ unité); String frespace = free.substring (0, free.length () - 1); Double Freespacel = Double.Parsedouble (Freespace); //System.out.println("free Spacel: "+ freespacel); if (unit.equals ("k")) {return frespacel * 1024; } else if (unit.equals ("m")) {return frespacel * 1024 * 1024; } else if (unit.equals ("g")) {return frespacel * 1024 * 1024 * 1024; } else if (unit.equals ("t")) {return frespacel * 1024 * 1024 * 1024 * 1024; } else if (unit.equals ("p")) {return frespacel * 1024 * 1024 * 1024 * 1024; } return 0; } / ** * Obtenez tous les sous-répertoires et fichiers dans le répertoire spécifié * @Param Directory * @return * @throws exception * / @SuppressWarnings ("RawTypes") public list <string> listFiles (String Directory) lève exception {vector fileList = null; List <string> filenamelist = new ArrayList <string> (); FileList = sftp.ls (répertoire); Iterator it = fileList.iterator (); while (it.hasnext ()) {string filename = ((channelsftp.lSentry) it.next ()). getFileName (); if (filename.startswith (".") || filename.startswith ("..")) {continuant; } filenamelist.add (nom de fichier); } retour filenamelist; } public boolean mkdir (String Path) {boolean flag = false; essayez {sftp.mkdir (path); Flag = true; } catch (sftPException e) {flag = false; } drapeau de retour; }}Testez-le
public static void main (String [] arg) lève une exception {ssh ssh = new ssh ("10.10.10.83", 22, "test", "test"); essayez {ssh.connect (); } catch (jschexception e) {e.printStackTrace (); } / * String RemotePath = "/ home / tfxiaozi /" + "webApp /"; essayez {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 (). Remplace ("", "")); //System.out.println (ssh.getfreedisk ()); / * List <string> list = ssh.listFiles ("webApp / test"); pour (String s: list) {System.out.println (s); } * / / * booléen 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); pour (String s: list) {System.out.println (s); } System.out.println ("OK"); } catch (exception e) {System.out.println ("Extrait a échoué ...."); } * / / * String command = "rm -rf / home / tfxiaozi / webapp1 /" + "Ink and Wash Chinese Studies"; String sss = ssh.execcommand (commande, true); System.out.println (SSS); * / / * String FindCommand = "Find / Home / Tfxiaozi / webApp1 / Ink et Wash Chinese Studies-Name 'index.html'"; String result = ssh.execcommand (findCommand, true); System.out.println (résultat); * / / * String path = ""; ssh.listFiles (RemotePath); * / / * ssh.deletedir ("/ home / tfxiaozi / webapp1", true); * / // Ce qui suit sera décompressé dans le répertoire WebApp1, webApp1 / test / xxx //ssh.execcommand("unzip /home/tfxiaozi/webapp1/test.zip -d / home / tfxiaozi / webapp1 ", true); // Les éléments suivants seront décompressés vers le / 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 "); / * booléen b = ssh.download ("d: /temp/test.zip", "webapp / test.zip"); System.out.println (b); * / //ssh.getharddiskinfo (); System.out.println (ssh.getFreedisk ()); ssh.disconnect (); } Ce qui précède consiste à utiliser Linux pour fonctionner directement, mais il convient de noter que pour les fichiers chinois, lors de la décompression, il peut y avoir du code brouillé lors du passage, et les paramètres doivent être ajoutés, tels que Unzip -o CP936 test.zip -d / home / tfxiaozi / test.
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.