RSS Feed for This PostCurrent Article

Java – Writing An Automated Telnet Client

Telnet is a common protocol that we normally used to connect to a remote server, especially in Linux or Unix environment. To programmatically automate a telnet session so that we can execute or retrieve information from a remote server can be easily done using Apache Commons Net.

Below is the code that can be used to do a ps -ef on the remote Linux/Unix server, and retrieve the output.

import org.apache.commons.net.telnet.TelnetClient;

import java.io.InputStream;
import java.io.PrintStream;

public class AutomatedTelnetClient {
private TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
private String prompt = “#”;

public AutomatedTelnetClient(String server, String user, String password) {
try {
// Connect to the specified server
telnet.connect(server, 23);

// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());

// Log the user on
readUntil(“login: “);
write(user);
readUntil(“Password: “);
write(password);

// Advance to a prompt
readUntil(prompt + ” “);
}
catch (Exception e) {
e.printStackTrace();
}
}

public void su(String password) {
try {
write(“su”);
readUntil(“Password: “);
write(password);
prompt = “#”;
readUntil(prompt + ” “);
}
catch (Exception e) {
e.printStackTrace();
}
}

public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length() – 1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar) {
if (sb.toString().endsWith(pattern)) {
return sb.toString();
}
}
ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}

public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}

public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + ” “);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}

public void disconnect() {
try {
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
try {
AutomatedTelnetClient telnet = new AutomatedTelnetClient(“127.0.0.1″,
“username”,
“password”);
telnet.sendCommand(“ps -ef “);
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

You need to modify the prompt variable so that it matches what you configured in the server.

I used it together with Twitter for remote server monitoring so that I can connect and execute commands on the servers behinds firewall from the DMZ.

Note: This is potential security threat if not used properly.


Trackback URL


RSS Feed for This Post26 Comment(s)

  1. subpop | Feb 13, 2008 | Reply

    Cool! fantastic! thanks

  2. James | Dec 17, 2008 | Reply

    Okay I need code that will compile. I got the source code for org.apache.commons.net.telnet.TelnetClient, saved it as a file and it does not compile. Not sure what I’m doing wrong.

  3. James Huang | Mar 30, 2009 | Reply

    It is a great job. One command is working properly. I tried to add several cammands in a loop, it only stay in the first command. I am not sure if this is the prompt. On SunOS, the prompt should be PS1 setting in the profile something like PS1=”`/usr/bin/uname -n`($LOGNAME)$PWD > “, so the prompt should be /usr/bin/uname -n`($LOGNAME)$PWD >. Could you please help?
    Thanks!

  4. Raja M | Jul 6, 2009 | Reply

    It is a great job. One command is working properly. I tried to add several commands in a loop, it only stay in the first command.can you help me pls

  5. Abdullah | Aug 20, 2009 | Reply

    Thank you it is great work.
    Guys I run commands in loop and it is working fine for me

  6. Julio | Feb 12, 2010 | Reply

    Hi Abdullah, can you tell me how can run commands in loop ????

    I tried to do that, but I don’t know how.

    thanks in advanced.

    Julio

  7. Abdullah | Apr 6, 2010 | Reply

    Hi Hulio,
    Just read the input stream and search the response after successful login. Write the command you want execute. like below code lines:

    if(s.endsWith(“>”)){
    write(“ls 000\n”);
    }

  8. Kiran | Sep 16, 2010 | Reply

    Hi
    I wamt to telnet other than default Port, i tried its not working.

    Please help.

    Thanks in advance……………

    Kiran

  9. madhavi | Sep 29, 2010 | Reply

    Hi,

    u code is working great. but ihave some problem executing a script that is present on my local machine. how can i execute it on the remote machine and copy the files to the local windows machine?

    Thanks in advance

  10. Ashish | Oct 7, 2010 | Reply

    Hi,
    your code is working fine. But can you help me to go forward.Actually I am trying to open multiple telnet sessions automatically with a single java code.

  11. Udaya | Feb 8, 2011 | Reply

    Hi,

    Thanks for the Post.

  12. sanarvi | May 26, 2011 | Reply

    Hi,

    This is a great piece of code, The only possible scenario I am suspecting is if we have the output having same value as prompt.

    If I am running a command that has a prompt
    ABC-425#

    and if i run a command
    ABC-425# show xyz

    Output is :
    aa
    bb
    cc#
    dd ee
    ff

    Then in the above scenario it will consider this cc# as the end of the command output.

    Any workaround for this kind of scenario given we cant change the prompt itself.

    as there are possibilities that whole prompt can be an output of some commands.

  13. krishna | Sep 14, 2011 | Reply

    telnet response is coming in the following format, pls help me.

    Authentication is in progress…←[2J←[1;1H←[0;37;40mMicrosoft←[1;11HWindows←[1;1
    9HXP←[1;22H[Version←[1;31H5.1.2600]←[2;1H(C)←[2;5HCopyright←[2;15H1985-2001←[2;2
    5HMicrosoft←[2;35HCorp.←[4;1HC:\>d:

  14. Mohit | Dec 28, 2011 | Reply

    Hi All,

    I want to use same thing in windows. but it shows “Session Timed out” what i need to do

  15. yelabbas | Jan 4, 2012 | Reply

    Thanks,
    you saved my night ;)

  16. yelabbas | Jan 4, 2012 | Reply

    Forget to tell that I used this telnet automation from an android app …

  17. hsk | Mar 20, 2012 | Reply

    using same piece code of code.working fine but if i m passing wrong command and expecting ‘>’ to end command there is an issue.

    (char) in.read();

    blocked for infinite and never returns.is there any command timeout option we can set with telnetclient?

  18. hsk | Apr 10, 2012 | Reply

    any update on above?

  19. andarius40 | May 11, 2012 | Reply

    Hello,

    I use this code for connecting to telnet.
    But I have a problem, because.
    I don’t have a prompt, for obtain this.
    I press ENTER.
    And I don’t know how i send ENTER with JAVA on TELNET connexion.

    Thanks for your help

  20. LeftN | May 19, 2012 | Reply

    @yelabbas
    I’m a Android/Java newbie trying to get this working on Android but struggling with getting it running in Eclipse :(

    Are there any sample eclipse projects I could look at running apache commons?

  21. anhhus | Dec 18, 2012 | Reply

    Where did you receive source code org.apache.commons.net.telnet.Telnet Client?

  22. Zebra Print Rugs | Jul 12, 2013 | Reply

    I was extremely pleased to uncover this web site. I need
    to to thank you for ones time just for this fantastic read!
    ! I definitely loved every little bit of it and i also have you saved as a favorite to look at new information on your site.

  23. forte Suites condo | Jul 13, 2013 | Reply

    hello there and thank you for your information – I have certainly picked up
    anything new from right here. I did however expertise several
    technical issues using this website, since I experienced to reload the website lots
    of times previous to I could get it to load correctly. I had been wondering if your web hosting is OK?
    Not that I am complaining, but slow loading instances times will sometimes
    affect your placement in google and can damage your high-quality score if
    ads and marketing with Adwords. Anyway I am adding this RSS
    to my email and could look out for a lot more of your respective interesting content.
    Ensure that you update this again very soon.

  24. Java Training in Chennai | Sep 24, 2013 | Reply

    Thanks for the code.

  25. content writing services | Jul 10, 2014 | Reply

    Usually I do not read post on blogs, however I would
    like to say that this write-up very compelled me to try and do so!
    Your writing style has been amazed me. Thanks, very great article.

  26. telnet router small linux distros | Aug 24, 2014 | Reply

    Hello there! Do you know if they make any plugins to assist with SEO?

    I’m trying to get my blog to rank for some targeted
    keywords but I’m not seeing very good success. If you know
    of any please share. Cheers!

1 Trackback(s)

  1. From [Java]Tomcat Restart 하기 | Pagong's DEV Life | Feb 11, 2012

RSS Feed for This PostPost a Comment

*