Some Applications of commons-net3

Source: Internet
Author: User
Tags ftp login

Example of FTP upload/download:

Import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import org.apache.commons.net. ftp. FTPClient; import org.apache.commons.net. ftp. FTPFile; import org.apache.commons.net. ftp. FTPReply; public class TestUploadDownload {/*** Description: upload a file to the FTP server * @ param url FTP Server hostname * @ param port FTP server port * @ param usern Ame FTP login account * @ param password FTP login password * @ param path FTP server storage directory * @ param filename file name uploaded to the FTP server * @ param input stream * @ return success return true, otherwise, false */public boolean uploadFile (String url, int port, String username, String password, String path, String filename, InputStream input) is returned) {// boolean success = false indicates that the Upload Failed; // create the FTPClient object FTPClient ftp = new FTPClient (); try {int reply; // connect to the FTP server // as shown in Figure If you use the default port, you can use ftp. connect (url) directly to the FTP Server ftp. connect (url, port); // log on to ftp. login (username, password); // check whether the returned value is 230. If yes, the login is successful. reply = ftp. getReplyCode (); // the return value starting with 2 is true if (! FTPReply. isPositiveCompletion (reply) {ftp. disconnect (); return success;} // go to the specified upload directory ftp. changeWorkingDirectory (path); // stores the uploaded file to the specified directory ftp. storeFile (filename, input); // close the input stream input. close (); // exit ftp. logout (); // indicates that the upload is successful. success = true;} catch (IOException e) {e. printStackTrace ();} finally {if (ftp. isConnected () {try {ftp. disconnect () ;}catch (IOException ioe) {}} return success; }/*** Description: download the file from the FTP server * @ param url FTP Server hostname * @ param port FTP server port * @ param username FTP login account * @ param password FTP login password * @ param remotePath FTP Server * @ param fileName: the file name to be downloaded * @ param localPath: The local path * @ return */public boolean downFile (String url, int port, String username, String password, String remotePath, String fileName, String localPath) {// indicates a download failure boolean succe Ss = false; // create FTPClient object FTPClient ftp = new FTPClient (); try {int reply; // connect to the FTP server // if the default port is used, you can use ftp. connect (url) directly to the FTP Server ftp. connect (url, port); // log on to ftp. login (username, password); reply = ftp. getReplyCode (); if (! FTPReply. isPositiveCompletion (reply) {ftp. disconnect (); return success;} // go to the specified download directory ftp. changeWorkingDirectory (remotePath); // list all the files in this directory. FTPFile [] fs = ftp. listFiles (); // traverse all files and find the specified file for (FTPFile ff: fs) {if (ff. getName (). equals (fileName) {// initialize the File localFile = new File (localPath + "/" + ff. getName (); // output stream OutputStream is = new FileOutputStream (localFile); // download the file ftp. retrieveFile (ff. getName (), is); is. close () ;}// exit ftp. logout (); // success = true;} catch (IOException e) {e. printStackTrace ();} finally {if (ftp. isConnected () {try {ftp. disconnect ();} catch (IOException ioe) {}} return success;}/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stub }}

Example of simulating telnet Logon:

Import java. io. inputStream; import java. io. printStream; import org.apache.commons.net. telnet. echoOptionHandler; import org.apache.commons.net. telnet. suppressGAOptionHandler; import org.apache.commons.net. telnet. telnetClient; import org.apache.commons.net. telnet. terminalTypeOptionHandler;/*** use the apache commons-net package to simulate telnet logon */public class TestTelnet {private TelnetClient telnet = null; private InputStream in; private PrintStream out; private char prompt = '#'; // linux prompt/*** log on to linux * @ param server * @ param user * @ param password */public TestTelnet (String server, string user, String password) {try {// Connect to the specified server telnet = new TelnetClient (); TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler ("VT100", false, false, true, false); EchoOptionHandler echoopt = new EchoOptionHandler (true, false, true, false); SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler (true, true); telnet. addOptionHandler (ttopt); telnet. addOptionHandler (echoopt); telnet. addOptionHandler (gaopt); telnet. connect (server, 23); // Get input and output stream references in = telnet. getInputStream (); out = new PrintStream (telnet. getOutputStream (); // Log the user on readUntil ("login:"); write (user); readUntil ("Password:"); write (password ); // Advance to a prompt readUntil ("$" + ""); // readUntil ("$" + "su = root "); // write ("su-root");} catch (Exception e) {e. printStackTrace ();}} /*** change the current logon user * @ param user Username * @ param password * @ param serTile linux user prompt * @ return */public String suUser (String user, String password, string userTitle) {// System. out. println ("Change current user:"); write ("su-" + user); // System. out. println ("prepare to read the returned stream to see if you can continue to enter the password:"); readUntil ("Password:"); // it may not be Chinese, use the telnet command to test // System. out. println ("the returned information prompts you to enter the password before starting to record the password:"); write (password); return readUntil (userTitle + "");} /*** read stream information ** @ param pattern the ending character when the stream is read * @ return */public String readUntil (String pattern) {try {char lastChar = pattern. charAt (pattern. length ()-1); // System. out. println ("current stream Character Set:" + new // InputStreamReader (in ). getEncoding (); StringBuffer sb = new StringBuffer (); byte [] buff = new byte [1024]; int ret_read = 0; String str = ""; do {ret_read = in. read (buff); if (ret_read> 0) {// transcode the characters in the read stream, you can use echo $ LANG on the linux host to view what encoding the System is String v = new String (buff, 0, ret_read, "UTF-8"); str = str + v; // System. out. println ("debug:" + str + "======" + pattern); if (str. endsWith (pattern) {// System. out. println ("Exit:" + str + "======" + pattern); break ;}} while (ret_read >= 0); return str ;} catch (Exception e) {e. printStackTrace ();} return null;}/*** sends a message to the stream * @ param value */public void write (String value) {try {out. println (value); out. flush (); System. out. println ("input command:" + value);} catch (Exception e) {e. printStackTrace () ;}}/*** run the command. The default linux prompt is '$' * @ param command * @ return */public String sendCommand (String command) {try {prompt = '$'; write (command); return readUntil (prompt + "") ;}catch (Exception e) {e. printStackTrace ();} return null;}/*** run the command, the default linux prompt is '$' * @ param command * @ param userTitle linux prompt * @ return */public String sendCommand (String command, char userTitle) {try {prompt = userTitle; write (command); return readUntil (prompt + "");} catch (Exception e) {e. printStackTrace ();} return null;}/*** release connection */public void disconnect () {try {telnet. disconnect ();} catch (Exception e) {e. printStackTrace () ;}/ *** @ param args */public static void main (String [] args) {try {TestTelnet telnet = new TestTelnet ("192.168.0.1 ", "zhsoft", "rootroot"); // use -- color = no to block the ls command color. Otherwise, garbled String reStr = telnet. sendCommand ("ls -- color = no"); System. out. println (reStr. replaceFirst ("ls -- color = no", ""); telnet. suUser ("root", "rootroot", "#"); String reStr2 = telnet. sendCommand ("ls -- color = no", '#'); System. out. println (reStr2.replaceFirst ("ls -- color = no", ""); telnet. disconnect ();} catch (Exception e) {e. printStackTrace ();}}}

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.