サーバーファイルのアップロードとSSHからダウンロードします
正面に書かれた言葉
以前に、ApacheのFTPオープンソースコンポーネントを使用してサーバーファイルをアップロードおよびダウンロードする方法を記録しましたが、後で削除すると許可の問題があることがわかりました。これにより、サーバー上のファイルを削除できないことがわかります。 WindowsでFilezillaサーバーを使用して読み取りおよび書き込みアクセス許可を設定した後に問題はありませんが、サーバー側で使用するのはまだ少し難しいです。
単一のファイルのFASTDFSストレージに加えて、リソース管理機能を実装する必要があるため、特定のリソースのストレージがサーバーに一時的に保存されることが計画されています。プロジェクトチームの同僚は、後でサーバーでFTPサービスを特に開かないと述べたため、SFTPモードに変更して操作しました。
このことの使い方
まず、JSCH JARパッケージをダウンロードする必要があります。アドレスはhttp://www.jcraft.com/jsch/です。ウェブサイトはまた非常に明確に書いています。JSCHはSSH2の純粋なJava実装です。これは、SSH2の純粋なJava実装です。 IPとポートを使用して、ユーザー名とパスワードを入力すると、それを正常に使用できます。これは、安全なCRTの使用方法と同じです。では、この便利なツールをどのように使用しますか?
実際、書くことができないかどうかは関係ありません。当局者も例を挙げました。リンクはhttp://www.jcraft.com/jsch/examples/shell.javaです。見てみましょう:
/* - * - モード:Java; C-Basic-Offset:2; indent-tabs-mode:nil - * - *// ***このプログラムを使用すると、SSHDサーバーに接続してシェルプロンプトを取得できます。 * $ classpath =。:../ javac shell.java * $ classpath =。:../ java shell * build java shell * username、hostname、passwdが求められます。 *すべてが正常に機能する場合、シェルプロンプトが表示されます。出力は、末端排出の欠如のために醜い場合がありますが、コマンドを発行できます。 **/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 ");文字列host = null; if(arg.length> 0){host = arg [0]; } else {host = joptionpane.showinputdialog( "username@hostname"をEntere.getProperty( "user.name")+ "@localhost"); } string user = host.substring(0、host.indexof( '@')); host = host.substring(host.indexof( '@')+1);セッションセッション= jsch.getSession(ユーザー、ホスト、22); string passwd = joptionpane.showinputdialog( "パスワードを入力"); session.setpassword(passwd); userInfo ui = new MyuserInfo(){public void showmessage(string message){joptionpane.showmessageialog(null、message); } public boolean emprospyesno(string message){object [] options = {"yes"、 "no"}; int foo = joptionpane.showoptiondialog(null、message、 "warning"、joptionpane.default_option、joptionpane.warning_message、null、options、options [0]); foo == 0を返します。 } //セッション#connect()の呼び出しの前にパスワードが指定されていない場合、//次のメソッドも実装します。 SESSION.SETUSERINFO(UI); //推奨する必要はありませんが、ホストキーチェックをスキップする場合は、// follow、// session.setconfig( "stricthostkeychecking"、 "no"); //session.connect(); session.connect(30000); //タイムアウトと接続します。チャネルチャネル= session.openchannel( "shell"); // Agent-Forwardingを有効にします。 //((CHANNELSHELL)Channel).setAgentForwarding(true); Channel.setInputStream(System.in); /* // Windows上のMS-DOSプロンプトのハック。 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); /* // pty-type "vt102"を選択します。 ((チャネルシェル)チャネル).setptyType( "vt102"); * / /* //環境変数「lang」を「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はuserinfo、uikeyboardinteractive {public string getpassword(){return null; } public boolean empspentyesno(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、string name、string string [] prompt、boolean [] echo){return null; }}}このコードでは、基本的に必要なものを見ることができます。まず、ユーザー情報を作成する必要があります。これは主に認証に使用されます。 userInfoとuikeyboardinteractiveの2つのインターフェイスを実装するだけです。次に、セッションセッションを作成することにより、userInfo inを設定し、最後に接続します。
カプセル化されたファイルのアップロードとダウンロード
上記は、JSCHの基本的な使用方法、つまりいくつかの基本的なルーチンです。使用する機能をカプセル化し、ファイルのアップロードやダウンロードなどの一連の操作を実装します。
最初に、userinfoを作成します:
public class myuserinfoはuserInfoを実装します。 } public boolean empspentyesno(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; }}これが実装クラスです。
パッケージcom.tfxiaozi.common.utils; import java.io.inputstream; Import java.util.arraylist; Import java.util.iterator; Import java.util.vector; Import java.util.vector; Import org.apache.log4j.logger; import com.jcraft.jsch.channel; com.jcraft.jsch.channelexec; Import com.jcraft.jsch.channelftp; Import com.jcraft.jsch.jsch; Import com.jcraft.jsch.jschexception; Import com.jcraft.jsch.session; import com.jcraft.jsch.sftexception; * @author tfxiaozi * */public class ssh {logger logger = logger.getLogger(this.getClass());プライベート文字列host = ""; private string user = ""; Private int port = 22;プライベート文字列password = ""; private static final string protocol = "sftp"; jsch jsch = new jsch();プライベートセッションセッション。プライベートチャネルチャネル。 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(パスワード); session.connect(); Channel = session.openchannel(protocol); channel.connect(); sftp =(channelsftp)チャネル; }} / ** * 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)スロー例外{boolean bsucc = false; try {sftpprogressmonitor Monitor = new MyProgressMonitor(); int mode = channelsftp.overwrite; sftp.put(localfilename、remotefilename、モニター、モード); bsucc = true; } catch(例外e){logger.error(e); }最後に{if(null!= channel){channel.disconnect(); }} bsuccを返します。 } / ** * delete file * @param directory * @param filename * @return * / public boolean detectectefile(string directory、string filename){boolean flag = false; try {sftp.cd(directory); sftp.rm(filename); flag = true; } catch(sftpexception e){flag = false; logger.error(e); } flagを返します。 } / ** * delete Directory * @param Directory dir be Delete * @param delete * @return * / public string deletedir(string directory、boolean sure){string command = "rm -rf" + directory; string result = execcommand(command、true);返品結果; }/** *ディレクトリのファイルとサブディールをCompressNameという名前のzipに圧縮します * @paramディレクトリコンテンツディレクトリは圧縮されます。 */public void compressdir(String Directory、String CompressName)STHOWS SFTPEXCEPTION {string command = "cd" + directory + "/nzip -r" + compressName + "./" + compressname.substring(0、compressname.lastindexof( "。"。 ")); execcommand(command、true); } / ** *ダウンロード * @param localfilename * @param remotefilename * @return * / public boolean download(string localfilename、string remotefilename){boolean bsucc = false;チャネルチャネル= null; try {sftpprogressmonitor Monitor = new MyProgressMonitor(); sftp.get(remotefileName、localfileName、Monitor、channelsftp.overwrite); bsucc = true; } catch(例外e){logger.error(e); }最後に{if(null!= channel){channel.disconnect(); }} bsuccを返します。 } / ** * execute command * @param command * @param flag * @return * / public string execomand(string command、boolean flag){channel 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)チャネル).seterrtream(system.err); in = channel.getInputStream(); channel.connect(); if(flag){byte [] tmp = new byte [10240]; while(true){while(in.abailable()> 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(例外e){logger.error(e); }最後に{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はin = channel.getinputStream()を追加する必要があります。 ((ChannelExec)チャネル).seterrtream(system.err); channel.connect(); byte [] tmp = new byte [10240]; while(true){while(in.abailable()> 0){int i = in.read(tmp、0、10240); if(i <0){break; } sb.append(new String(TMP、0、i)); } if(channel.isclosed()){break; }}} catch(例外e){logger.error(e); }最後に{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"); } / ** *ハードディスク情報を取得 * @return * / public string getharddiskinfo()スロー例外{チャネルチャネル= null; inputstream in = null; stringbuffer sb = new StringBuffer( ""); try {channel = session.openchannel( "exec"); ((ChannelExec)Channel).SetCommand( "df -lh"); in = channel.getInputStream(); ((ChannelExec)チャネル).seterrtream(system.err); channel.connect(); byte [] tmp = new byte [10240]; while(true){while(in.abailable()> 0){int i = in.read(tmp、0、10240); if(i <0){break; } sb.append(new String(TMP、0、i)); } if(channel.isclosed()){break; }}} catch(例外e){新しいruntimeexception(e); }最後に{if(channel!= null){channel.disconnect(); }} string buf = sb.toString(); string [] info = buf.split( "/n"); if(info.length> 2){// first line:files -systemサイズ使用利用可能な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] + "sude" + result [3] + "free";壊す; } else {buf = ""; }}}} else {buf = ""; } bufを返します。 } / ** * free bytesの数を返します * @return * @throws例外 * / public double getFreedisk()スロー例外{String harddiskinfo = getharddiskinfo(); if(harddiskinfo == null || harddiskinfo.equals( "")){logger.error( "get free harddiskスペースが失敗しました......"); return -1; } string [] diskinfo = harddiskinfo.replace( "" "、" ").split("、 "); if(diskinfo == null || diskinfo.length == 0){logger.error( "無料ディスク情報が失敗します......"); return -1; } string free = diskinfo [2]; free = free.substring(0、free.indexof( "free")); //system.out.println("free space: " + 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; } return 0; } / ** *指定されたディレクトリのすべてのサブディレクトリとファイルを取得 * @Param Directory * @return * @Throws Exception * / @SuppressWarnings( "RawTypes")public List <string> listFiles(string directory)throws {vector filelist = null; List <String> filenameList = new ArrayList <String>(); filelist = sftp.ls(ディレクトリ); iterator it = fileList.iterator(); while(it.hasnext()){string filename =((channelsftp.lsentry)it.next())。getFileName(); if(filename.startswith( "。")|| filename.startswith( "..")){継続; } filenameList.add(filename); } filenameListを返します。 } public boolean mkdir(string path){boolean flag = false; {sftp.mkdir(path); flag = true; } catch(sftpexception e){flag = false; } flagを返します。 }}それをテストします
public static void main(string [] arg)throws exception {ssh ssh = new ssh( "10.10.10.83"、22、 "test"、 "test"); try {ssh.connect(); } catch(jschexception e){e.printstacktrace(); }/*文字列remotepath = "/home/tfxiaozi/" + "webapp/"; try {ssh.listfiles(remotepath); } catch(例外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()。置換( ""、 "")); //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( "抽出失敗...."); }*//*string command = "rm -rf/home/tfxiaozi/webapp1/" + "インクと洗浄中国の研究"; string sss = ssh.execcommand(command、true); System.out.Println(SSS);*//*String findCommand = "Find/Home/Tfxiaozi/webApp1/InkおよびWash Chinese Study-name 'index.html'";文字列result = ssh.execcommand(findcommand、true); system.out.println(result);* / /*string path = ""; ssh.listfiles(remotepath);*//* ssh.deletedir( "/home/tfxiaozi/webApp1"、true); *///以下は、webApp1ディレクトリ、webApp1/test/xxx //ssh.execcommand( "unzip /home/tfxiaozi/webapp1/test.zip -d/home/tfxiaozi/webapp1"、trueに減圧されます。 //以下は/webApp1/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(); }上記はLinuxを使用して直接動作することですが、中国のファイルについては、渡されると、渡されるときにコードが刻まれている可能性があり、UNZIP -O CP936 test.zip -d/home/tfxiaozi/テストなど、パラメーターを追加する必要があることに注意してください。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。