我正在使用org.apache.commons.net.telnet库与我的Telnet服务器建立连接,该服务器的实现与标准的RFC 854略有不同,但并不太可怕。
实际上,建立到这个远程telnet服务器的连接的唯一方法是利用org.apache.commons.net.telnet,因为纯Java没有工作。
由于无法找到使用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
}
}
}长话短说:我如何使用这个库发送命令?
发布于 2016-11-29 13:42:10
您可以使用从OutputStream返回的getOutputStream编写数据,例如telnet.getOutputStream().write(cmd);。您可能也需要在.flush()上调用OutputStream
https://stackoverflow.com/questions/40866414
复制相似问题