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:org.openhab.binding.heos.internal.resources.Telnet.java

public Telnet() {
    client = new TelnetClient();
}

From source file:org.openhab.binding.lutron.internal.net.TelnetSession.java

public TelnetSession() {
    this.telnetClient = new TelnetClient();
    this.charBuffer = CharBuffer.allocate(BUFSIZE);

    this.telnetClient.setReaderThread(true);
    this.telnetClient.registerInputListener(new TelnetInputListener() {
        @Override//w  w  w .  j a va 2s.  c o m
        public void telnetInputAvailable() {
            try {
                readInput();
            } catch (IOException e) {
                notifyInputError(e);
            }
        }
    });
}

From source file:org.opennaas.extensions.transports.telnet.TelnetTransport.java

public void connect() throws TransportException {
    logger.info("Telnet Transport trying to connect...");

    // Create a new telnet client
    telnetClient = new TelnetClient();

    // VT100 terminal type will be subnegotiated
    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    // WILL SUPPRESS-GA, DO SUPPRESS-GA options
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
    // WON'T ECHO, DON'T ECHO
    EchoOptionHandler echoopt = new EchoOptionHandler();

    try {//from   w  w w. ja  v  a  2 s .  c om
        // set telnet client options
        telnetClient.addOptionHandler(ttopt);
        telnetClient.addOptionHandler(gaopt);
        telnetClient.addOptionHandler(echoopt);

        // connect
        telnetClient.connect(host, Integer.parseInt(port));

        // set the read timeout
        telnetClient.setSoTimeout(READ_TIMEOUT);

        // Initialize the print writer
        outPrint = new PrintWriter(telnetClient.getOutputStream(), true);
    } catch (Exception e) {
        e.printStackTrace();
        throw new TransportException("Could not connect, unable to open telnet session " + e.getMessage());
    }
}

From source file:org.openo.nfvo.monitor.dac.dataaq.datacollector.cli.telnet.TelnetSession.java

public TelnetSession() {
    cmdEcho = true;//from  ww w  .  j a  va2s  .  c  om
    promptEcho = true;

    telnetClient = new TelnetClient();
    try {
        telnetClient.addOptionHandler(windowSize);
    } catch (InvalidTelnetOptionException | IOException e) {
        LOGGER.error("Failed to add WindowSizeOptionHandler.", e);
    }
}

From source file:org.openremote.controller.protocol.telnet.TelnetCommand.java

public void send(boolean readResponse) {
    TelnetClient tc = null;/*w  ww.j  a va 2 s  . c  o m*/
    if (readResponse) {
        setResponse("");
    }
    try {
        tc = new TelnetClient();
        tc.connect(getIp(), Integer.parseInt(getPort()));
        StringTokenizer st = new StringTokenizer(getCommand(), "|");
        int count = 0;
        if (getCommand().startsWith("|")) {
            count++;
        }
        String waitFor = "";
        while (st.hasMoreElements()) {
            String cmd = (String) st.nextElement();
            if (count % 2 == 0) {
                waitFor = cmd;
                if (!"null".equals(cmd)) {
                    waitForString(cmd, tc);
                }
            } else {
                sendString(cmd, tc);
                if (readResponse) {
                    readString(waitFor, tc);
                }
            }
            count++;
        }
    } catch (Exception e) {
        logger.error("could not perform telnetEvent", e);
    } finally {
        if (tc != null) {
            try {
                tc.disconnect();
            } catch (IOException e) {
                logger.error("could not disconnect from telnet", e);
            }
        }
    }
}

From source file:org.owasp.goatdroid.gui.emulator.Emulator.java

static public void sendLocation(String latitude, String longitude) throws SocketException, IOException {

    TelnetClient telnet = new TelnetClient();
    telnet.setDefaultPort(5554);/*from w  ww .j  av a2s . co  m*/
    telnet.connect("localhost");
    PrintStream outStream = new PrintStream(telnet.getOutputStream());
    // geo fix takes longitude/latitude, in that order
    outStream.println("geo fix " + longitude + " " + latitude);
    outStream.flush();
}

From source file:org.owasp.goatdroid.gui.emulator.Emulator.java

static public void sendSMSToEmulator(String phoneNumber, String message) throws SocketException, IOException {

    TelnetClient telnet = new TelnetClient();
    telnet.setDefaultPort(5554);// ww w.j  av a 2s . c  o m
    telnet.connect("localhost");
    PrintStream outStream = new PrintStream(telnet.getOutputStream());
    outStream.println("sms send " + phoneNumber + " " + message);
    outStream.flush();

}

From source file:org.owasp.goatdroid.gui.emulator.Emulator.java

static public void callEmulator(String phoneNumber) throws SocketException, IOException {

    TelnetClient telnet = new TelnetClient();
    telnet.setDefaultPort(5554);/* w ww.j  av  a2 s  . c o  m*/
    telnet.connect("localhost");
    PrintStream outStream = new PrintStream(telnet.getOutputStream());
    outStream.println("gsm call " + phoneNumber);
    outStream.flush();

}

From source file:org.smartfrog.services.net.TelnetImpl.java

/**
 * Connects to remote host and executes commands.
 *
 * @throws SmartFrogException in case of error in connecting to remote host
 *                            ,executing commands or command output is same
 *                            as failure message provided in the component
 *                            desciption.
 * @throws RemoteException    in case of network/emi error
 *//*from   w  w  w.  ja v  a 2s  .com*/
@Override
public synchronized void sfStart() throws SmartFrogException, RemoteException {
    super.sfStart();
    FileOutputStream fout = null;
    try {
        // create optional log file for the telnet session
        try {
            if (logFile != null) {
                fout = new FileOutputStream(logFile, false);
            }
        } catch (IOException ioex) {
            sfLog().error("Error in opening log file:" + ioex, ioex);
        }

        client = new TelnetClient();
        String destination = "" + host + ":" + port;
        sfLog().debug("Connecting to " + destination);
        try {
            client.connect(host, port);
        } catch (IOException e) {
            throw new SmartFrogDeploymentException("Failed to connect to " + destination, e, this);
        }

        OutputStream opStream = client.getOutputStream();
        InputStream inpStream = client.getInputStream();
        sfLog().debug("Waiting for prompt '" + PROMPT_LOGIN + "'");
        String failureCause = "";
        boolean operationStatus = waitForString(inpStream, PROMPT_LOGIN, timeout);
        sfLog().debug(" result: " + operationStatus);
        if (operationStatus) {
            String loginName = user + '\n';
            opStream.write(loginName.getBytes());
            opStream.flush();
            String prompt;
            if (OSTYPE_LINUX.equals(ostype)) {
                prompt = PROMPT_LINUX_PASSWORD;
            } else if (OS_TYPE_WINDOWS.equals(ostype)) {
                prompt = PROMPT_WINDOWS_PASSWORD;
            } else {
                throw new SmartFrogDeploymentException("Unknown " + Telnet.OSTYPE + " value '" + ostype + "'",
                        this);
            }
            operationStatus = waitForString(inpStream, prompt, timeout);
            if (!operationStatus) {
                failureCause = "Failed to get password prompt '" + prompt + "' expected for ostype " + ostype;
            }
        } else {
            failureCause = "Failed to get login prompt '" + PROMPT_LOGIN + "'";
        }
        String passwordDetails = (password == null) ? "NO PASSWORD" : "password length " + password.length();

        sfLog().debug("Entering password");
        if (operationStatus) {
            String passWd = password + '\n';
            opStream.write(passWd.getBytes());
            opStream.flush();
            sfLog().debug("Waiting for shell prompt '" + shellPrompt + "'");
            LoginResults results = attemptLogin(inpStream, shellPrompt, timeout);
            if (!results.promptFound) {
                operationStatus = false;
                failureCause = "User \"" + user + "\" was not known, " + " their password was invalid "
                        + " or the shell prompt \"" + shellPrompt + "\" was not found." + " Password details: "
                        + passwordDetails + " \n" + " remote server log: " + results.received;
            }

        }
        if (!operationStatus) {
            throw new SmartFrogLifecycleException(
                    "Unable to login in remote machine " + destination + " cause: " + failureCause, this);
        }

        //at this point, we are successfully logged in

        if (sfLog().isInfoEnabled()) {
            sfLog().info("Successful login to:" + destination);
        }

        // register the output stream and set to null
        FileOutputStream fout1 = fout;
        fout = null;
        client.registerSpyStream(fout1);
        boolean checkCmdExecStatus = false;
        if ((cmdsFailureMsgs != null) && (!cmdsFailureMsgs.isEmpty())) {
            checkCmdExecStatus = true;
        }
        // Execute commands
        for (int i = 0; i < commandsList.size(); i++) {
            String cmd = commandsList.get(i);
            sfLog().debug("Executing " + cmd);
            cmd = cmd + '\n';
            opStream.write(cmd.getBytes());
            opStream.flush();

            // wait for prompt to return.
            waitForString(inpStream, shellPrompt, timeout);

            // check if command was successfully executed
            if (checkCmdExecStatus) {
                String errMsg = cmdsFailureMsgs.get(i);
                sfLog().debug("Waiting for error message " + errMsg);
                boolean execError = waitForString(inpStream, errMsg, timeout);
                if (execError) {
                    // throw exception
                    throw new SmartFrogTelnetException(cmd, errMsg);
                }
            }

        }

        ComponentHelper helper = new ComponentHelper(this);
        TerminationRecord termR = TerminationRecord.normal("Telnet session to " + destination + " finished: ",
                sfCompleteName());
        helper.sfSelfDetachAndOrTerminate(termR);

    } catch (Exception e) {
        throw SmartFrogLifecycleException.forward(e);
    } finally {
        //stop the client if defined
        if (client != null) {
            client.stopSpyStream();
        }
        //and the output stream, if not null.
        FileSystem.close(fout);
    }
}

From source file:org.smslib.modem.IPModemDriver.java

void connectPort() throws GatewayException, IOException, InterruptedException {
    try {// w w w . j a  va 2  s  . c  o m
        gateway.logInfo("Opening: " + ipAddress + " @" + ipPort);
        tc = new TelnetClient();
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
        tc.connect(ipAddress, ipPort);
        in = tc.getInputStream();
        out = tc.getOutputStream();
        peeker = new Peeker();
    } catch (InvalidTelnetOptionException e) {
        throw new GatewayException("Unsupported telnet option for the selected IP connection.");
    }
}