栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

寻找Java Telnet模拟器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

寻找Java Telnet模拟器

在这里找到了我想要的东西:http : //twit88.com/blog/2007/12/22/java-writing-an-
automated-telnet-client/

您将需要修改提示变量。

代码副本:

import org.apache.commons.net.telnet.TelnetClient;import java.io.InputStream;import java.io.PrintStream;public class AutomatedTelnetClient {    private TelnetClient telnet = new TelnetClient();    private InputStream in;    private PrintStream out;    private String prompt = "%";    public AutomatedTelnetClient(String server, String user, String password) {        try { // Connect to the specified server 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(prompt + " ");        } catch (Exception e) { e.printStackTrace();        }    }    public void su(String password) {        try { write("su"); readUntil("Password: "); write(password); prompt = "#"; readUntil(prompt + " ");        } catch (Exception e) { e.printStackTrace();        }    }    public String readUntil(String pattern) {        try { char lastChar = pattern.charAt(pattern.length() - 1); StringBuffer sb = new StringBuffer(); boolean found = false; char ch = (char) in.read(); while (true) {     System.out.print(ch);     sb.append(ch);     if (ch == lastChar) {         if (sb.toString().endsWith(pattern)) {  return sb.toString();         }     }     ch = (char) in.read(); }        } catch (Exception e) { e.printStackTrace();        }        return null;    }    public void write(String value) {        try { out.println(value); out.flush(); System.out.println(value);        } catch (Exception e) { e.printStackTrace();        }    }    public String sendCommand(String command) {        try { write(command); return readUntil(prompt + " ");        } catch (Exception e) { e.printStackTrace();        }        return null;    }    public void disconnect() {        try { telnet.disconnect();        } catch (Exception e) { e.printStackTrace();        }    }    public static void main(String[] args) {        try { AutomatedTelnetClient telnet = new AutomatedTelnetClient(         "myserver", "userId", "Password"); System.out.println("Got Connection..."); telnet.sendCommand("ps -ef "); System.out.println("run command"); telnet.sendCommand("ls "); System.out.println("run command 2"); telnet.disconnect(); System.out.println("DONE");        } catch (Exception e) { e.printStackTrace();        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/496566.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号