java中telnet访问远程电脑,然后执行cmd命令,再获取返回值。

dolphin29 2013-10-14 05:33:14
我的电脑是A,并且在A上有虚拟机B,我想在A上用java的telnet访问B,然后执行cmd命令,再获取返回信息(例如用ipconfig获取B的ip地址,然后在A上返回)。 a和b都是windows
我在网上找了一部分代码,看是基本看懂了,但是运行了好像不行,据说这些代码不是用于windows的:

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

import java.io.InputStream;
import java.io.PrintStream;

public class TelnetTest
{
private TelnetClient telnet = new TelnetClient();

private InputStream in;

private PrintStream out;

private char prompt = '$';// 普通用户结束

public TelnetTest(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 {
TelnetTest she =new TelnetTest("192.168.1.2", 23, "Administrator", "abc");
System.out.println(she);
System.out.println(she.sendCommand("dspmq"));
she.disconnect();

}catch (Exception e) {
// TODO: handle exception
}

}
}
...全文
424 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
普凡 2013-10-15
  • 打赏
  • 举报
回复
引用 1 楼 kk_124 的回复:
代码机制没有问题: 只是在登陆时各种操作系统输入(判别字符串)有所不同 你把 / 根据root用户设置结束符 那句代码注释 试一试
还有就是结束符prompt变量不一样
普凡 2013-10-15
  • 打赏
  • 举报
回复
代码机制没有问题: 只是在登陆时各种操作系统输入(判别字符串)有所不同 你把 / 根据root用户设置结束符 那句代码注释 试一试

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧