ome*_*itz 2 java apache telnet
我正在使用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
}
}
}
Run Code Online (Sandbox Code Playgroud)
长话短说:如何使用这个库发送命令?
您可以使用从 返回的 OutputStream 写入数据getOutputStream,例如telnet.getOutputStream().write(cmd);。您可能也需要调用.flush()OutputStream
| 归档时间: |
|
| 查看次数: |
4627 次 |
| 最近记录: |