I'm using org.apache.commons.net.telnet
library to establish a connection with my Telnet server which has a slightly different implementation than the standard RFC 854, but nothing too scary.
Actually, the only way for me to establish a connection to this remote telnet server is to utilize the org.apache.commons.net.telnet
, since the pure Java Socket didn't work.
I'm stucked with this library since I can't figure out a way to send commans with it using sendCommand
method, which accepts a byte
(not byte[]
) for it's one and only argument.
I convert my String command
into a byte[]
array but I can't pass that as an argument...
This is my code so far:
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
}
}
}
Long story short: How can I send commands using this library?
You can write data using the OutputStream returned from getOutputStream
, e.g. telnet.getOutputStream().write(cmd);
. You might need to call .flush()
on the OutputStream too