【发布时间】:2017-04-13 11:31:59
【问题描述】:
我正在使用 org.apache.commons.net.telnet 库与我的 Telnet 服务器建立连接,该服务器的实现与标准 RFC 854 略有不同,但没什么可怕的。
实际上,我与这个远程 telnet 服务器建立连接的唯一方法是使用org.apache.commons.net.telnet,因为纯 Java Socket 不起作用。
我被这个库困住了,因为我想不出一种使用sendCommand 方法发送命令的方法,该方法接受byte(不是byte[]),因为它是唯一的参数。
我将 String command 转换为 byte[] 数组,但我不能将其作为参数传递...
这是我目前的代码:
import org.apache.commons.net.io.Util;
import org.apache.commons.net.telnet.TelnetClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Telnet {
public static void main(String[] args) {
TelnetClient telnet;
telnet = new TelnetClient();
try {
telnet.connect("17.16.15.14", 12345);
byte[] cmd = "root".getBytes();
telnet.sendCommand(cmd); // this is where I'm stuck
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
readWrite(telnet.getInputStream(), telnet.getOutputStream(),
System.in, System.out);
try {
telnet.disconnect();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
System.exit(0);
}
public static final void readWrite(final InputStream remoteInput,
final OutputStream remoteOutput,
final InputStream localInput,
final OutputStream localOutput)
{
Thread reader, writer;
reader = new Thread()
{
@Override
public void run()
{
int ch;
try
{
while (!interrupted() && (ch = localInput.read()) != -1)
{
remoteOutput.write(ch);
remoteOutput.flush();
}
}
catch (IOException e)
{
//e.printStackTrace();
}
}
}
;
writer = new Thread()
{
@Override
public void run()
{
try
{
Util.copyStream(remoteInput, localOutput);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
};
writer.setPriority(Thread.currentThread().getPriority() + 1);
writer.start();
reader.setDaemon(true);
reader.start();
try
{
writer.join();
reader.interrupt();
}
catch (InterruptedException e)
{
// Ignored
}
}
}
长话短说:如何使用这个库发送命令?
【问题讨论】: