Example usage for org.apache.commons.net.telnet TelnetClient TelnetClient

List of usage examples for org.apache.commons.net.telnet TelnetClient TelnetClient

Introduction

In this page you can find the example usage for org.apache.commons.net.telnet TelnetClient TelnetClient.

Prototype

public TelnetClient() 

Source Link

Document

Default TelnetClient constructor, sets terminal-type VT100 .

Usage

From source file:configurator.Configurator.java

Telnet(String login, String password, String ip) throws IOException {
    solidMark = Configurator.mainProperites.getProperty("solid_command_mark");
    ipMark = Configurator.mainProperites.getProperty("ip_command_mark");
    this.login = login;
    this.password = password;
    this.ip = ip;
    int port = Integer.valueOf(Configurator.mainProperites.getProperty("Telnet_Port"));
    telnet = new TelnetClient();
    telnet.connect(ip, port);/* ww  w  .  j  a  v  a  2 s .c om*/
    in = telnet.getInputStream();
    out = new PrintStream(telnet.getOutputStream());
}

From source file:com.sjc.cc.login.action.LoginAction.java

private String getInterfaceStrs() {

    StringBuffer buf = new StringBuffer();
    buf.append("<table>");
    HostConnectionStatus hostStatus = new HostConnectionStatus();
    String proxyIp = Config.getProperty("mail.send.host");
    try {/*from   ww w .j a  v a2 s  .com*/

        TelnetClient telnet = new TelnetClient();
        telnet.connect(proxyIp, 25);// ????
        telnet.disconnect();
        hostStatus.setOaGatewayConStatus(true);
    } catch (Exception ex) {

        logger.error("<<<<<<<<<<<?.", ex);
        hostStatus.setOaGatewayConStatus(false);
    }

    try {

        /*CPIC_InterfaceForm_ChangeRequest_CreateGet_WSServiceStub sub1 = new CPIC_InterfaceForm_ChangeRequest_CreateGet_WSServiceStub();
        sub1._getServiceClient().getServiceContext();
        sub1 = null;*/
        hostStatus.setRemedyConStatus(true);
    } catch (Exception ex) {

        logger.error("<<<<<<<<<<<Remedy?.", ex);
        hostStatus.setRemedyConStatus(false);
    }

    hostStatus.setCmdbConStatus(outService.cmdbValidation());
    hostStatus.setNewResStatus(outService.csValidation());

    if (hostStatus.isCmdbConStatus()) {

        buf.append("<tr>");
        buf.append("<td><font>CMDB</font></td><td><span class='Rstate_green' title=''></span></td>");
        buf.append("</tr>");
    } else {

        buf.append("<tr>");
        buf.append("<td><font>CMDB</font></td><td><span class='Rstate_red' title=''></span></td>");
        buf.append("</tr>");
    }

    if (hostStatus.isNewResStatus()) {

        buf.append("<tr>");
        buf.append(
                "<td><font>?</font></td><td><span class='Rstate_green' title=''></span></td>");
        buf.append("</tr>");
    } else {

        buf.append("<tr>");
        buf.append(
                "<td><font>?</font></td><td><span class='Rstate_red' title=''></span></td>");
        buf.append("</tr>");
    }

    Map<String, Boolean> map = outService.vcValidation();
    Set<String> set = map.keySet();
    buf.append("<tr><td><font>??</font></td><td>");
    for (String ip : set) {
        if (map.get(ip).booleanValue()) {

            buf.append("<span class='Rstate_green' title='" + ip + "'></span>");
        } else {

            buf.append("<span class='Rstate_red' title='" + ip + "'></span>");
        }
    }
    buf.append("</td></tr>");

    if (hostStatus.isRemedyConStatus()) {

        buf.append("<tr>");
        buf.append("<td><font>Remedy</font></td><td><span class='Rstate_green' title=''></span></td>");
        buf.append("</tr>");
    } else {

        buf.append("<tr>");
        buf.append("<td><font>Remedy</font></td><td><span class='Rstate_red' title=''></span></td>");
        buf.append("</tr>");
    }

    if (hostStatus.isOaGatewayConStatus()) {

        buf.append("<tr>");
        buf.append(
                "<td><font>OA</font></td><td><span class='Rstate_green' title=''></span></td>");
        buf.append("</tr>");
    } else {
        buf.append("<tr>");
        buf.append("<td><font>OA</font></td><td><span class='Rstate_red' title=''></span></td>");
        buf.append("</tr>");
    }
    buf.append("</table>");

    return buf.toString();
}

From source file:it.infn.ct.jsaga.adaptor.rocci.job.rOCCIJobControlAdaptor.java

@Override
public String submit(String jobDesc, boolean checkMatch, String uniqId)
        throws PermissionDeniedException, TimeoutException, NoSuccessException, BadResource {
    String resourceID = "";
    String publicIP = "";
    //List<String> results = new ArrayList();
    List<String> results = new ArrayList<String>();

    if (action.equals("create")) {

        log.info("Creating a new OCCI computeID. Please wait! ");

        if (attributes_title.trim().length() > 0)
            log.info("VM Title     = " + attributes_title);

        if (mixin_os_tpl.trim().length() > 0)
            log.info("OS           = " + mixin_os_tpl);

        if (mixin_resource_tpl.trim().length() > 0)
            log.info("Flavour      = " + mixin_resource_tpl);

        String Execute = prefix + "occi --endpoint " + Endpoint + " --action " + "create" + " --resource "
                + resource + " --attribute occi.core.title=" + attributes_title + " --mixin os_tpl#"
                + mixin_os_tpl + " --mixin resource_tpl#" + mixin_resource_tpl + " --auth " + auth
                + " --user-cred " + user_cred + " --voms --ca-path " + ca_path;

        log.info("");
        log.info(Execute);//from w  w  w  .ja  v a2 s .  co  m

        try {
            results = run_OCCI("create", Execute);
            if (results.isEmpty())
                throw new NoSuccessException("Some problems occurred while executing the action create. "
                        + "Please check your settings.");

        } catch (Exception ex) {
            log.error(ex);
        }

        // Getting info about the VM
        if (results.size() > 0) {
            resourceID = results.get(0);

            int k = 0;
            boolean check = false;

            try {
                while (!check) {
                    log.info("");
                    log.info("See below the details of the VM ");
                    log.info("[ " + resourceID + " ]");
                    log.info("");

                    Execute = prefix + "occi --endpoint " + Endpoint + " --action " + "describe"
                            + " --resource " + resource + " --resource " + resourceID + " --auth " + auth
                            + " --user-cred " + user_cred + " --voms --ca-path " + ca_path
                            + " --output-format json_extended_pretty";

                    log.info(Execute);

                    results = run_OCCI("describe", Execute);

                    publicIP = getIP(results);
                    if (!isNullOrEmpty(publicIP))
                        check = true;
                    else
                        check = true;
                } // end while
            } catch (Exception ex) {
                log.error(ex);
            }

            sshControlAdaptor.setSecurityCredential(credential.getSSHCredential());
            log.info("");
            log.info("Starting VM [ " + publicIP + " ] in progress...");

            Date date = new Date();
            SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

            log.info("");
            log.info("Waiting the remote VM finishes the boot! Sleeping for a while... ");
            log.info(ft.format(date));

            byte[] buff = new byte[1024];
            int ret_read = 0;
            boolean flag = true;
            int MAX = 0;

            TelnetClient tc = null;

            while ((flag) && (MAX < MAX_CONNECTIONS)) {
                try {
                    tc = new TelnetClient();
                    tc.connect(publicIP, 22);
                    InputStream instr = tc.getInputStream();

                    ret_read = instr.read(buff);
                    if (ret_read > 0) {
                        log.info("[ SUCCESS ] ");
                        tc.disconnect();
                        flag = false;
                    }
                } catch (IOException e) {

                    try {
                        Thread.sleep(60000);
                    } catch (InterruptedException ex) {
                    }

                    MAX++;
                }
            }

            date = new Date();
            log.info(ft.format(date));
        }

        rOCCIJobMonitorAdaptor.setSSHHost(publicIP);

        try {
            sshControlAdaptor.connect(null, publicIP, 22, null, new HashMap());
        } catch (NotImplementedException ex) {
            throw new NoSuccessException(ex);
        } catch (AuthenticationFailedException ex) {
            throw new PermissionDeniedException(ex);
        } catch (AuthorizationFailedException ex) {
            throw new PermissionDeniedException(ex);
        } catch (BadParameterException ex) {
            throw new NoSuccessException(ex);
        }

        return sshControlAdaptor.submit(jobDesc, checkMatch, uniqId) + "@" + publicIP + "#" + resourceID;
    } // end creating

    else
        return null;
}

From source file:controllers.TNodes.java

/**
 * //from ww w . j ava  2s.co  m
 */
public static void conTest() {
    String nodeId = params.get("tNodeIdTest");
    System.out.println(nodeId);
    TNode tNode = TNode.findById(Long.parseLong(nodeId));
    String ip = tNode.T_NODE_IP;
    String user = tNode.T_NODE_ACCOUNT;
    String password = tNode.T_NODE_PWD;
    String type = tNode.T_NODE_LOGINTYPE;
    if (type.equalsIgnoreCase("ssh")) {
        // System.out.println("" + type);
        SSHClient sshClient = new SSHClient();
        if (sshClient.connect(ip, user, password)) {
            sshClient.disconnect();
            renderText("true");
        } else {
            renderText("false");
        }

    } else if (type.equalsIgnoreCase("telnet")) {
        // System.out.println("" + type);
        TelnetClient telnetClient = new TelnetClient();
        if (connect(ip, user, password, telnetClient)) {
            renderText("true");
        } else {
            renderText("false");
        }
    } else {
        // System.out.println("" + type);
        String line1 = "$para_ip='" + ip + "'";
        String line2 = "$para_name='" + user + "'";
        String line3 = "$para_serverpass='" + password + "'";
        String line4 = "$para_password=ConvertTo-SecureString $para_serverpass -AsPlainText -Force";
        String line5 = "$para_object=New-Object system.management.automation.pscredential($para_name,$para_password)";
        String line6 = "Invoke-Command -computername $para_ip -credential $para_object -scriptblock {echo  '===ScriptOver==='}";
        String line7 = "remove-item $MyInvocation.MyCommand.Path -force";
        String[] infos = { line1, line2, line3, line4, line5, line6, line7 };
        try {
            StringBuffer buf = new StringBuffer();
            // ???
            for (int j = 0; j < infos.length; j++) {
                buf = buf.append(infos[j]);
                buf = buf.append(System.getProperty("line.separator"));
            }
            CommonUtil.createShell(localPath + "/" + tNode.id.toString() + ".ps1", buf.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String scriptTest = PSClient
                .execCommand("powershell -f " + localPath + "/" + tNode.id.toString() + ".ps1");
        if (scriptTest.trim().equals("===ScriptOver===")) {
            renderText("true");
        } else {
            renderText("false");
        }
    }

}

From source file:it.infn.ct.jsaga.adaptor.jocci.job.jOCCIJobControlAdaptor.java

@Override
public String submit(String jobDesc, boolean checkMatch, String uniqId)
        throws PermissionDeniedException, TimeoutException, NoSuccessException, BadResource {
    String result = "";
    //String networkInterfaceLocation = "";
    //String networkInterfaceLocation_stripped = "";
    //Resource vm_resource = null;
    String publicIP = "";

    if (action.equals("create")) {
        try {/*  w  w  w  .  j a va  2s . c  om*/
            log.info("Creating a new resource using jOCCI-api. Please wait!");

            if (attributes_title.trim().length() > 0)
                log.info("VM Title     = " + attributes_title);

            if (mixin_os_tpl.trim().length() > 0)
                log.info("OS           = " + mixin_os_tpl);

            if (mixin_resource_tpl.trim().length() > 0)
                log.info("Flavour      = " + mixin_resource_tpl);

            log.info("");
            if (context_publickey.equals("true")) {
                log.info("EGI FedCloud Contextualisation options:");

                log.info("org.openstack.credentials.publickey.data = "
                        + getPublicKey(credential.getSSHCredential().getPublicKeyFile().getPath()));

                log.info("org.openstack.credentials.publickey.name = " + context_publickey_name);
            } else
                log.info("No contextualization set for the resource.");

            HTTPAuthentication authentication = new VOMSAuthentication(user_cred);

            authentication.setCAPath(ca_path);
            /*Client client = new HTTPClient(URI.create("https://"
                + OCCI_ENDPOINT_HOST + ":"
                + OCCI_ENDPOINT_PORT),
                authentication, MediaType.TEXT_PLAIN, false);*/

            Client client = new HTTPClient(URI.create(protocol + OCCI_ENDPOINT_HOST + ":" + OCCI_ENDPOINT_PORT),
                    authentication, MediaType.TEXT_PLAIN, false);

            //connect client
            client.connect();

            Model model = client.getModel();
            EntityBuilder eb = new EntityBuilder(model);
            Date date = new Date();

            log.info("");
            log.info("[ TEMPLATES ]");
            log.info("- Available os templates mixins ...");
            List<Mixin> mixins = model.findRelatedMixins("os_tpl");

            if (!mixins.isEmpty()) {
                for (Mixin entry : mixins)
                    log.info(entry);

                // 1.) Create a new compute resource
                log.info("");
                log.info("[ CREATE ]");
                Resource compute = eb.getResource("compute");
                Mixin mixin = model.findMixin(mixin_os_tpl);
                compute.addMixin(mixin);
                compute.addMixin(model.findMixin(mixin_os_tpl, "os_tpl"));
                compute.addMixin(model.findMixin(mixin_resource_tpl, "resource_tpl"));
                if (context_publickey.equals("true")) {
                    // Add SSH public key 
                    compute.addMixin(model.findMixin(
                            URI.create("http://schemas.openstack.org/instance/credentials#public_key")));
                    compute.addAttribute("org.openstack.credentials.publickey.name", context_publickey_name);

                    compute.addAttribute("org.openstack.credentials.publickey.data",
                            getPublicKey(credential.getSSHCredential().getPublicKeyFile().getPath()));
                }

                compute.setTitle(attributes_title);
                log.info(mixin.toText());

                log.info("");
                // Creating a new VM resource
                URI location = client.create(compute);

                // Getting the list of available running resources
                List<URI> list = client.list();
                URI uri_location = list.get(0);
                // Listing all the active resources
                //URI uri_location = null;
                log.info("[ LIST ]");
                log.info("- Retieve the list of VMs running on the cloud site");

                for (URI uri : list) {
                    if (uri.toString().contains("compute")) //{
                        log.info("~ " + uri);
                    //uri_location = uri;
                    //}
                }

                log.info("");
                log.info("================= [ R E P O R T ] =================");

                // 3.) Describe resource
                log.info("");
                log.info("[ DESCRIPTION ]");
                if (location != null) {
                    log.info("- Getting VM settings for the resource");
                    log.info(uri_location);
                } else
                    log.error("Some errors occurred during the creation of a new resource.");

                List<Entity> entities = client.describe(uri_location);
                Resource resource = (Resource) entities.get(0);
                vm_resource = resource;
                log.info(entities.get(0).toText());

                SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

                log.info("");
                log.info("Waiting the remote VM finishes the boot!");
                log.info(ft.format(date));

                log.info("");
                log.info("Waiting the status of the following resource becomes ACTIVE");
                log.info(uri_location);
                log.info("This operation may take few minutes to complete. Please wait!");
                log.info("");

                try {
                    Thread.sleep(60000);
                } catch (InterruptedException ex) {
                    java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE,
                            null, ex);
                }

                while (!entities.get(0).getValue(Compute.STATE_ATTRIBUTE_NAME).equals("active")) {
                    log.info("[ STATUS ] = " + entities.get(0).getValue(Compute.STATE_ATTRIBUTE_NAME));

                    entities = client.describe(uri_location);

                    if (entities.get(0).getValue(Compute.STATE_ATTRIBUTE_NAME).equals("active")) {
                        log.info("[ STATUS ] = " + entities.get(0).getValue(Compute.STATE_ATTRIBUTE_NAME));

                        try {
                            Thread.sleep(30000);
                        } catch (InterruptedException ex) {
                            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName())
                                    .log(Level.SEVERE, null, ex);
                        }

                        // Getting IP address and NetworkLocation 
                        // of the resource
                        String IP = getNetworkLocation(entities)[0];

                        log.info("");
                        log.info("The compute resource is now active!");
                        log.info("URI = " + uri_location);
                        log.info("IP  = " + IP);
                        log.info("");
                        log.info("Check whether the compute resource has a public IP or not ");

                        if (checkIP(IP) != null) {
                            log.info("The compute resource has a *public* IP [ " + IP + " ]");
                            publicIP = IP;
                        } else {
                            log.info("The compute resource has a *private* IP [ " + IP + " ]");

                            // Find a network resource that provides public IPs 
                            String public_network = "";
                            List<URI> uris = client.list("network");
                            log.info("Listing available networks for the given resource");
                            if (!uris.isEmpty()) {
                                // Listing networks
                                for (URI uri : uris) {
                                    //if ((uri.toString()).contains("public"))
                                    if ((uri.toString()).contains(OCCI_PUBLIC_NETWORK_ID))
                                        public_network = uri.toString();

                                    log.info("NetworkID = " + uri.toString());
                                }
                            }

                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException ex) {
                                java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }

                            if (public_network != null && !public_network.isEmpty()) {
                                log.info("");
                                log.info("Public Network = " + public_network);
                                log.info("Unlink the network interface that doesn't have public IPs");
                                log.info("NetworkID = " + getNetworkLocation(entities)[1]);
                                client.delete(URI.create((getNetworkLocation(entities)[1])));

                                IPNetworkInterface ipni = eb.getIPNetworkInterface();
                                ipni.setSource(vm_resource);
                                ipni.setTarget(public_network);
                                location = client.create(ipni);

                                // Sleeping for a while
                                try {
                                    Thread.sleep(5000);
                                } catch (InterruptedException ex) {
                                    ex.printStackTrace(System.out);
                                }

                                log.info("");
                                log.info("[ DESCRIPTION ]");
                                entities = client.describe(uri_location);
                                log.info(entities.get(0).toText());

                                String tmp = "";
                                log.info("");
                                log.info("- Get the available IPs for the given VM");
                                for (Entity entity : entities) {
                                    resource = (Resource) entity;
                                    Set<Link> links = resource.getLinks(NetworkInterface.TERM_DEFAULT);

                                    for (Link link : links) {
                                        tmp = link.getValue(IPNetworkInterface.ADDRESS_ATTRIBUTE_NAME);
                                        log.info("IP = " + tmp);
                                        if (checkIP(tmp) != null)
                                            publicIP = tmp;
                                    }
                                } // end-for
                            } // end-if
                        } // end-else

                        log.info("Public IP address = " + publicIP);
                        log.info("Checking for connectivity. Please wait! ");

                        byte[] buff = new byte[1024];
                        int ret_read = 0;
                        boolean flag = true;
                        int MAX = 0;
                        TelnetClient tc = null;

                        while ((flag) && (MAX < MAX_CONNECTIONS)) {
                            try {
                                tc = new TelnetClient();
                                tc.connect(publicIP, 22);
                                InputStream instr = tc.getInputStream();

                                ret_read = instr.read(buff);
                                if (ret_read > 0) {
                                    log.info("SSH daemon has started [ OK ] ");
                                    tc.disconnect();
                                    flag = false;
                                }
                            } catch (IOException e) {
                                log.info("The destination host is unreachable. Sleeping for a while... ");
                                try {
                                    Thread.sleep(60000);
                                } catch (InterruptedException ex) {
                                    java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName())
                                            .log(Level.SEVERE, null, ex);
                                }

                                MAX++;
                            }
                        } // end-while

                        date = new Date();
                        log.info(ft.format(date));

                        jOCCIJobMonitorAdaptor.setSSHHost(publicIP);

                        try {
                            sshControlAdaptor.connect(null, publicIP, 22, null, new HashMap());
                        } catch (NotImplementedException ex) {
                            throw new NoSuccessException(ex);
                        } catch (AuthenticationFailedException ex) {
                            throw new PermissionDeniedException(ex);
                        } catch (AuthorizationFailedException ex) {
                            throw new PermissionDeniedException(ex);
                        } catch (BadParameterException ex) {
                            throw new NoSuccessException(ex);
                        }

                        result = sshControlAdaptor.submit(jobDesc, checkMatch, uniqId) + "@" + publicIP + "#"
                                + uri_location;

                        break;
                    } else {
                        try {
                            // Sleeping for a while ...
                            Thread.sleep(5000);
                        } catch (InterruptedException ex) {
                            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName())
                                    .log(Level.SEVERE, null, ex);
                        }
                    } //end-else
                } //end-while

            } else
                log.error("No OS template mixins available!");

        } catch (RenderingException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        } catch (InvalidAttributeValueException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        } catch (EntityBuildingException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        } catch (AmbiguousIdentifierException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        } catch (CommunicationException ex) {
            java.util.logging.Logger.getLogger(jOCCIJobControlAdaptor.class.getName()).log(Level.SEVERE, null,
                    ex);
        }
    } // end creating

    return result;
}

From source file:org.alfresco.maven.plugin.AbstractRefreshWebappMojo.java

/**
 * Utility method to ping/call the Alfresco Tomcat server and see if it is up (running)
 *
 * @return true if the Alfresco Tomcat server was reachable and up
 *///  w  w  w  .  j  a  v  a  2s. c  o  m
private boolean ping() {
    try {
        URL alfrescoTomcatUrl = buildFinalUrl("");
        TelnetClient telnetClient = new TelnetClient();
        telnetClient.setDefaultTimeout(500);
        telnetClient.connect(alfrescoTomcatUrl.getHost(), alfrescoTomcatUrl.getPort());
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:org.apache.common.net.examples.telnet.MyTelnetClientExample.java

private static void checkByTelnet(Map.Entry<String, String> entry, int port) {
    String remoteHost = entry.getKey();
    String remoteIp = entry.getValue();
    int remotePort = port;

    final TelnetClient tc = new TelnetClient();
    try {//from   w  w  w. j  a  va 2s .  co  m
        tc.connect(remoteHost, remotePort);
    } catch (ConnectException exception) {
        System.out.println("catch ConnectException to");
        errorList.add("can't connect to " + remoteIp + "(" + remoteHost + ")" + " by port " + port);
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        tc.disconnect();
    } catch (IOException e) {
        System.err.println("Exception while connecting:" + e.getMessage());
    }
}

From source file:org.apache.commons.net.examples.telnet.TelnetClientExample.java

/***
 * Main for the TelnetClientExample./*from   w ww  .  jav a 2s  .c o m*/
 * @param args input params
 * @throws Exception on error
 ***/
public static void main(String[] args) throws Exception {
    FileOutputStream fout = null;

    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample <remote-ip> [<remote-port>]");
        System.exit(1);
    }

    String remoteip = args[0];

    int remoteport;

    if (args.length > 1) {
        remoteport = Integer.parseInt(args[1]);
    } else {
        remoteport = 23;
    }

    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");
            System.out.println("Type ^[A-Z] to send the control character; use ^^ to send ^");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        final String line = new String(buff, 0, ret_read); // deliberate use of default charset
                        if (line.startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if (line.startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if (line.startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if (line.startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if (line.startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if (line.startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else if (line.matches("^\\^[A-Z^]\\r?\\n?$")) {
                            byte toSend = buff[1];
                            if (toSend == '^') {
                                outstr.write(toSend);
                            } else {
                                outstr.write(toSend - 'A' + 1);
                            }
                            outstr.flush();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:org.apache.commons.net.examples.telnet.WeatherTelnet.java

public static final void main(String[] args) {
    TelnetClient telnet;//from w  ww . ja v a  2  s  .  c  o m

    telnet = new TelnetClient();

    try {
        telnet.connect("rainmaker.wunderground.com", 3000);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    IOUtil.readWrite(telnet.getInputStream(), telnet.getOutputStream(), System.in, System.out);

    try {
        telnet.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    System.exit(0);
}

From source file:org.apache.james.remotemanager.RemoteManagerTest.java

protected void connect() throws IOException {
    m_telnetClient = new TelnetClient();
    m_telnetClient.connect(m_host, m_remoteManagerListenerPort);

    m_reader = new BufferedReader(
            new InputStreamReader(new BufferedInputStream(m_telnetClient.getInputStream(), 1024), "ASCII"));
    m_writer = new InternetPrintWriter(new BufferedOutputStream(m_telnetClient.getOutputStream(), 1024), true);

    readAnswer(3);//  ww w . jav a2 s  .c o  m
}