當前位置:編程學習大全網 - 源碼下載 - java代碼訪問telnet,並受到返回值

java代碼訪問telnet,並受到返回值

import java.io.InputStream;

import java.io.PrintStream;

import org.apache.commons.net.telnet.TelnetClient;

public class Shell {

private TelnetClient telnet = new TelnetClient();

private InputStream in;

private PrintStream out;

private char prompt = '$';// 普通用戶結束

public Shell(String ip, int port, String user, String password) {

try {

telnet.connect(ip, port);

in = telnet.getInputStream();

out = new PrintStream(telnet.getOutputStream());

// 根據root用戶設置結束符

this.prompt = user.equals("root") ? '#' : '>';

login(user, password);

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 登錄

*

* @param user

* @param password

*/

public void login(String user, String password) {

// read()Until("login:");

readUntil("login:");

write(user);

readUntil("Password:");

write(password);

readUntil(prompt + "");

}

/**

* 讀取分析結果

*

* @param pattern

* @return

*/

public String readUntil(String pattern) {

try {

char lastChar = pattern.charAt(pattern.length() - 1);

StringBuffer sb = new StringBuffer();

char ch = (char) in.read();

while (true) {

sb.append(ch);

if (ch == lastChar) {

if (sb.toString().endsWith(pattern)) {

return sb.toString();

}

}

ch = (char) in.read();

System.out.print(ch);

}

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 寫操作

*

* @param value

*/

public void write(String value) {

try {

out.println(value);

out.flush();

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 向目標發送命令字符串

*

* @param command

* @return

*/

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) {

// TelnetClient telnet = new TelnetClient();

try {

Shell she = new Shell("192.168.1.10", 23, "root", "123456");

System.out.println(she);

//執行的命令

System.out.println(she.sendCommand("ll"));

she.disconnect();

} catch (Exception e) {

// TODO: handle exception

}

}

}

  • 上一篇:如何戒掉手淫?
  • 下一篇:易語言des源代碼
  • copyright 2024編程學習大全網