commons-net3的一些应用

FTP上传下载的例子:

[java]  view plain  copy
  1. import java.io.File;     
  2. import java.io.FileOutputStream;     
  3. import java.io.IOException;     
  4. import java.io.InputStream;     
  5. import java.io.OutputStream;     
  6.     
  7. import org.apache.commons.net.ftp.FTPClient;     
  8. import org.apache.commons.net.ftp.FTPFile;     
  9. import org.apache.commons.net.ftp.FTPReply;     
  10.     
  11. public class TestUploadDownload {     
  12.     
  13.     /**   
  14.     * Description: 向FTP服务器上传文件   
  15.     * @param url FTP服务器hostname   
  16.     * @param port FTP服务器端口   
  17.     * @param username FTP登录账号   
  18.     * @param password FTP登录密码   
  19.     * @param path FTP服务器保存目录   
  20.     * @param filename 上传到FTP服务器上的文件名   
  21.     * @param input    输入流   
  22.     * @return 成功返回true,否则返回false   
  23.     */    
  24.     public boolean uploadFile(String url, int port, String username,     
  25.             String password, String path, String filename, InputStream input) {     
  26.         // 初始表示上传失败     
  27.         boolean success = false;     
  28.         // 创建FTPClient对象     
  29.         FTPClient ftp = new FTPClient();     
  30.         try {     
  31.             int reply;     
  32.             // 连接FTP服务器     
  33.             // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器     
  34.             ftp.connect(url, port);     
  35.             // 登录ftp     
  36.             ftp.login(username, password);     
  37.             // 看返回的值是不是230,如果是,表示登陆成功     
  38.             reply = ftp.getReplyCode();     
  39.             // 以2开头的返回值就会为真     
  40.             if (!FTPReply.isPositiveCompletion(reply)) {     
  41.                 ftp.disconnect();     
  42.                 return success;     
  43.             }     
  44.             // 转到指定上传目录     
  45.             ftp.changeWorkingDirectory(path);     
  46.             // 将上传文件存储到指定目录     
  47.             ftp.storeFile(filename, input);     
  48.             // 关闭输入流     
  49.             input.close();     
  50.             // 退出ftp     
  51.             ftp.logout();     
  52.             // 表示上传成功     
  53.             success = true;     
  54.         } catch (IOException e) {     
  55.             e.printStackTrace();     
  56.         } finally {     
  57.             if (ftp.isConnected()) {     
  58.                 try {     
  59.                     ftp.disconnect();     
  60.                 } catch (IOException ioe) {     
  61.                 }     
  62.             }     
  63.         }     
  64.         return success;     
  65.     }     
  66.          
  67.      /**   
  68.     * Description: 从FTP服务器下载文件   
  69.     * @param url FTP服务器hostname   
  70.     * @param port   FTP服务器端口   
  71.     * @param username FTP登录账号   
  72.     * @param password   FTP登录密码   
  73.     * @param remotePath   FTP服务器上的相对路径   
  74.     * @param fileName 要下载的文件名   
  75.     * @param localPath 下载后保存到本地的路径   
  76.     * @return   
  77.     */    
  78.     public boolean downFile(String url, int port, String username,     
  79.             String password, String remotePath, String fileName,     
  80.             String localPath) {     
  81.         // 初始表示下载失败     
  82.         boolean success = false;     
  83.         // 创建FTPClient对象     
  84.         FTPClient ftp = new FTPClient();     
  85.         try {     
  86.             int reply;     
  87.             // 连接FTP服务器     
  88.             // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器     
  89.             ftp.connect(url, port);     
  90.             // 登录ftp     
  91.             ftp.login(username, password);     
  92.             reply = ftp.getReplyCode();     
  93.             if (!FTPReply.isPositiveCompletion(reply)) {     
  94.                 ftp.disconnect();     
  95.                 return success;     
  96.             } // 转到指定下载目录     
  97.             ftp.changeWorkingDirectory(remotePath);     
  98.             // 列出该目录下所有文件     
  99.             FTPFile[] fs = ftp.listFiles();     
  100.             // 遍历所有文件,找到指定的文件     
  101.             for (FTPFile ff : fs) {     
  102.                 if (ff.getName().equals(fileName)) {     
  103.                     // 根据绝对路径初始化文件     
  104.                     File localFile = new File(localPath + "/" + ff.getName());     
  105.                     // 输出流     
  106.                     OutputStream is = new FileOutputStream(localFile);     
  107.                     // 下载文件     
  108.                     ftp.retrieveFile(ff.getName(), is);     
  109.                     is.close();     
  110.                 }     
  111.             }     
  112.             // 退出ftp     
  113.             ftp.logout();     
  114.             // 下载成功     
  115.             success = true;     
  116.         } catch (IOException e) {     
  117.             e.printStackTrace();     
  118.         } finally {     
  119.             if (ftp.isConnected()) {     
  120.                 try {     
  121.                     ftp.disconnect();     
  122.                 } catch (IOException ioe) {     
  123.                 }     
  124.             }     
  125.         }     
  126.         return success;     
  127.     }     
  128.          
  129.     /**   
  130.      * @param args   
  131.      */    
  132.     public static void main(String[] args) {     
  133.         // TODO Auto-generated method stub     
  134.     
  135.     }     
  136.     
  137. }    

模拟telnet登录的例子:

[java]  view plain  copy
  1. import java.io.InputStream;     
  2. import java.io.PrintStream;     
  3.     
  4. import org.apache.commons.net.telnet.EchoOptionHandler;     
  5. import org.apache.commons.net.telnet.SuppressGAOptionHandler;     
  6. import org.apache.commons.net.telnet.TelnetClient;     
  7. import org.apache.commons.net.telnet.TerminalTypeOptionHandler;     
  8.     
  9. /**   
  10. * 使用apache的commons-net包模拟telnet登录   
  11. */    
  12. public class TestTelnet {     
  13.     
  14.     private TelnetClient telnet = null;     
  15.     private InputStream in;     
  16.     private PrintStream out;     
  17.     private char prompt = '#';  //linux提示符     
  18.          
  19.     /**   
  20.     * 登录linux   
  21.     * @param server   
  22.     * @param user   
  23.     * @param password   
  24.     */    
  25.     public TestTelnet(String server, String user, String password) {     
  26.         try {     
  27.             // Connect to the specified server     
  28.             telnet = new TelnetClient();     
  29.             TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler(     
  30.                     "VT100"falsefalsetruefalse);     
  31.             EchoOptionHandler echoopt = new EchoOptionHandler(truefalse,     
  32.                     truefalse);     
  33.             SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true,     
  34.                     truetruetrue);     
  35.     
  36.             telnet.addOptionHandler(ttopt);     
  37.             telnet.addOptionHandler(echoopt);     
  38.             telnet.addOptionHandler(gaopt);     
  39.     
  40.             telnet.connect(server, 23);     
  41.     
  42.             // Get input and output stream references     
  43.             in = telnet.getInputStream();     
  44.     
  45.             out = new PrintStream(telnet.getOutputStream());     
  46.     
  47.             // Log the user on     
  48.             readUntil("login: ");     
  49.             write(user);     
  50.     
  51.             readUntil("Password: ");     
  52.             write(password);     
  53.     
  54.             // Advance to a prompt     
  55.             readUntil("$" + " ");     
  56.     
  57.             // readUntil("$" + "su = root");     
  58.             // write("su - root");     
  59.     
  60.         } catch (Exception e) {     
  61.             e.printStackTrace();     
  62.         }     
  63.     }     
  64.     
  65.     /**   
  66.      * 改变当前登录用户   
  67.      * @param user 用户名   
  68.      * @param password 密码   
  69.      * @param serTile linux用户提示符   
  70.      * @return   
  71.      */    
  72.     public String suUser(String user, String password, String userTitle) {     
  73.         // System.out.println("改变当前用户:");     
  74.         write("su - " + user);     
  75.         // System.out.println("准备读取返回的流,看是不是可以继续录入密码了:");     
  76.         readUntil("密码:");// 有可能不是中文,先用telnet命令测试下     
  77.         // System.out.println("返回信息提示可以录入密码,才开始录密码:");     
  78.         write(password);     
  79.         return readUntil(userTitle + " ");     
  80.     }     
  81.     
  82.     /**   
  83.      * 读取流信息   
  84.      * @param pattern 流读取时的结束字符   
  85.      * @return   
  86.      */    
  87.     public String readUntil(String pattern) {     
  88.         try {     
  89.             char lastChar = pattern.charAt(pattern.length() - 1);     
  90.             // System.out.println("当前流的字符集:"+new     
  91.             // InputStreamReader(in).getEncoding());     
  92.             StringBuffer sb = new StringBuffer();     
  93.             byte[] buff = new byte[1024];     
  94.             int ret_read = 0;     
  95.             String str = "";     
  96.             do {     
  97.                 ret_read = in.read(buff);     
  98.                 if (ret_read > 0) {     
  99.                     // 把读取流的字符转码,可以在linux机子上用echo $LANG查看系统是什么编码     
  100.                     String v = new String(buff, 0, ret_read, "UTF-8");     
  101.                     str = str + v;     
  102.                     // System.out.println("debug:"+str+"========"+pattern);     
  103.                     if (str.endsWith(pattern)) {     
  104.                         // System.out.println("退出:"+str+"========"+pattern);     
  105.                         break;     
  106.                     }     
  107.                 }     
  108.     
  109.             } while (ret_read >= 0);     
  110.             return str;     
  111.         } catch (Exception e) {     
  112.             e.printStackTrace();     
  113.         }     
  114.         return null;     
  115.     }     
  116.     
  117.     /**   
  118.      * 向流中发送信息   
  119.      * @param value   
  120.      */    
  121.     public void write(String value) {     
  122.         try {     
  123.             out.println(value);     
  124.             out.flush();     
  125.             System.out.println("录入命令:" + value);     
  126.         } catch (Exception e) {     
  127.             e.printStackTrace();     
  128.         }     
  129.     }     
  130.     
  131.     /**   
  132.      * 运行命令,默认linux提示符是'$'   
  133.      * @param command 命令   
  134.      * @return   
  135.      */    
  136.     public String sendCommand(String command) {     
  137.         try {     
  138.             prompt = '$';     
  139.             write(command);     
  140.             return readUntil(prompt + " ");     
  141.         } catch (Exception e) {     
  142.             e.printStackTrace();     
  143.         }     
  144.         return null;     
  145.     }     
  146.     
  147.     /**   
  148.      * 运行命令,默认linux提示符是'$'   
  149.      * @param command 命令   
  150.      * @param userTitle linux提示符   
  151.      * @return   
  152.      */    
  153.     public String sendCommand(String command, char userTitle) {     
  154.         try {     
  155.             prompt = userTitle;     
  156.             write(command);     
  157.             return readUntil(prompt + " ");     
  158.         } catch (Exception e) {     
  159.             e.printStackTrace();     
  160.         }     
  161.         return null;     
  162.     }     
  163.     
  164.     /**   
  165.      * 释放连接   
  166.      */    
  167.     public void disconnect() {     
  168.         try {     
  169.             telnet.disconnect();     
  170.         } catch (Exception e) {     
  171.             e.printStackTrace();     
  172.         }     
  173.     }     
  174.          
  175.     /**   
  176.      * @param args   
  177.      */    
  178.     public static void main(String[] args) {     
  179.         try {     
  180.             TestTelnet telnet = new TestTelnet("192.168.0.1""zhsoft""rootroot");     
  181.             // 使用--color=no屏蔽ls命令的颜色,要不会有乱码     
  182.             String reStr = telnet.sendCommand("ls --color=no");     
  183.             System.out.println(reStr.replaceFirst("ls --color=no"""));     
  184.             telnet.suUser("root""rootroot""#");     
  185.             String reStr2 = telnet.sendCommand("ls --color=no"'#');     
  186.             System.out.println(reStr2.replaceFirst("ls --color=no"""));     
  187.             telnet.disconnect();     
  188.         } catch (Exception e) {     
  189.             e.printStackTrace();     
  190.         }     
  191.     }     
  192.     
  193. }    

猜你喜欢

转载自blog.csdn.net/M_Jack/article/details/80337853
今日推荐