Hello all,
I'm relatively new to Java and to Commons. I am trying to code a class that
would telnet to a server and run a command. The examples with the Commons
source code include a class that connects to a weather server and I'm trying
to adapt that. My problem is that the example uses threads, which I am
woefully unfamiliar with. Below is my first stab. It gets to the point of
the "login:" line on the server and then hangs.
I'm asking for help/critique on any part of what I've written. I've been
playing with variations of this and scouring the jakarta and the
java.sun.com sites for a couple of days with no real progress. Please
excuse the long post; I'm afraid I'll leave out important info by trimming
it down.
Thanks,
Maury Jarrell
package my.package;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import org.apache.commons.net.telnet.TelnetClient;
public class RunCommand
{
StringBuffer sb = new StringBuffer();
InputStream tIn;
PrintWriter tOut;
class CmdReader extends Thread
{
public void run()
{
readFromServer();
}
}
class CmdWriter extends Thread
{
public void run()
{
writeToServer();
}
}
public synchronized void readFromServer()
{
int ch;
try
{
__READIT:
while ((ch = tIn.read()) != -1)
{
if ((char)ch == '\n')
{
System.out.println(sb.toString());
System.out.flush();
sb.delete(0, sb.length());
}
else
{
sb.append((char)ch);
}
}
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
public synchronized void writeToServer()
{
boolean secondPass = false;
__THREAD:
while (true)
{
try
{
if ((sb.indexOf("login:")) != -1)
{
sb.delete(0, sb.length());
System.out.println("Sending username.");
tOut.println("userName");
}
else if ((sb.indexOf("password")) != -1)
{
sb.delete(0,sb.length());
System.out.println("Sending password.");
tOut.println("password");
}
else if ((sb.indexOf("> ")) != -1)
{
if (!secondPass)
{
secondPass = true;
sb.delete(0,sb.length());
System.out.println("Sending command");
tOut.println("ls -l /usr");
}
else
{
break __THREAD;
}
}
notify();
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public void doCmd()
{
TelnetClient telnet;
CmdWriter writer = new CmdWriter();
CmdReader reader = new CmdReader();
telnet = new TelnetClient();
try
{
telnet.connect("server");
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
tIn = telnet.getInputStream();
tOut = new PrintWriter(telnet.getOutputStream());
try
{
reader.start();
writer.start();
writer.join();
reader.interrupt();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
try
{
telnet.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
System.exit(0);
}
public static void main(String[] args)
{
RunCommand rc = new RunCommand();
rc.doCmd();
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]