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:com.zte.ums.zenap.itm.agent.plugin.linux.util.cli.TelnetSession.java

public TelnetSession() {
    cmdEcho = true;// ww  w. ja  v  a 2 s  . c  o m
    promptEcho = true;

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

From source file:interactivespaces.util.command.expect.TelnetExpectClient.java

/**
 * Construct a telnet expect client with a standard telnet client.
 *
 * @param executorService/*from  ww w. j a  va  2  s. c o  m*/
 *          the executor service to use
 * @param log
 *          the log to use
 */
public TelnetExpectClient(ScheduledExecutorService executorService, Log log) {
    this(new TelnetClient(), executorService, log);
}

From source file:li.klass.fhem.fhem.TelnetConnection.java

public RequestResult<String> executeCommand(String command, Context context) {
    LOG.info("executeTask command {}", command);

    final TelnetClient telnetClient = new TelnetClient();
    telnetClient.setConnectTimeout(getConnectionTimeoutMilliSeconds(context));

    BufferedOutputStream bufferedOutputStream = null;
    PrintStream printStream = null;

    String errorHost = serverSpec.getIp() + ":" + serverSpec.getPort();
    try {/*  ww w .  ja  v a  2  s  .com*/
        telnetClient.connect(serverSpec.getIp(), serverSpec.getPort());

        OutputStream outputStream = telnetClient.getOutputStream();
        InputStream inputStream = telnetClient.getInputStream();

        bufferedOutputStream = new BufferedOutputStream(outputStream);
        printStream = new PrintStream(outputStream);

        boolean passwordSent = false;
        String passwordRead = readUntil(inputStream, PASSWORD_PROMPT);
        if (passwordRead != null && passwordRead.contains(PASSWORD_PROMPT)) {
            LOG.info("sending password");
            writeCommand(printStream, serverSpec.getPassword());
            passwordSent = true;
        }

        writeCommand(printStream, "\n\n");

        if (!waitForFilledStream(inputStream, 5000)) {
            return new RequestResult<>(RequestResultError.HOST_CONNECTION_ERROR);
        }

        // to discard
        String toDiscard = read(inputStream);
        LOG.debug("discarding {}", toDiscard);

        writeCommand(printStream, command);

        // If we send an xmllist, we are done when finding the closing FHZINFO tag.
        // If another command is used, the tag ending delimiter is obsolete, not found and
        // therefore not used. We just read until the stream ends.
        String result;
        if (command.equals("xmllist")) {
            result = readUntil(inputStream, "</FHZINFO>");
        } else {
            result = read(inputStream);
        }

        if (result == null && passwordSent) {
            return new RequestResult<>(RequestResultError.AUTHENTICATION_ERROR);
        } else if (result == null) {
            return new RequestResult<>(RequestResultError.INVALID_CONTENT);
        }

        telnetClient.disconnect();

        int startPos = result.indexOf(", try help");
        if (startPos != -1) {
            result = result.substring(startPos + ", try help".length());
        }

        startPos = result.indexOf("<");
        if (startPos != -1) {
            result = result.substring(startPos);
        }

        result = result.replaceAll("Bye...", "").replaceAll("fhem>", "");
        result = new String(result.getBytes("UTF8"));
        LOG.debug("result is {}", result);

        return new RequestResult<>(result);

    } catch (SocketTimeoutException e) {
        LOG.error("timeout", e);
        setErrorInErrorHolderFor(e, errorHost, command);
        return new RequestResult<>(RequestResultError.CONNECTION_TIMEOUT);
    } catch (UnsupportedEncodingException e) {
        // this may never happen, as UTF8 is known ...
        setErrorInErrorHolderFor(e, errorHost, command);
        throw new IllegalStateException("unsupported encoding", e);
    } catch (SocketException e) {
        // We handle host connection errors directly after connecting to the server by waiting
        // for some token for some seconds. Afterwards, the only possibility for an error
        // is that the FHEM server ends the connection after receiving an invalid password.
        LOG.error("SocketException", e);
        setErrorInErrorHolderFor(e, errorHost, command);
        return new RequestResult<>(RequestResultError.AUTHENTICATION_ERROR);
    } catch (IOException e) {
        LOG.error("IOException", e);
        setErrorInErrorHolderFor(e, errorHost, command);
        return new RequestResult<>(RequestResultError.HOST_CONNECTION_ERROR);
    } finally {
        CloseableUtil.close(printStream, bufferedOutputStream);
    }
}

From source file:eu.europa.ec.fisheries.uvms.plugins.inmarsat.twostage.Connect.java

public String connect(PollType poll, String path, String url, String port, String user, String psw, String dnid)
        throws TelnetException {

    String response = null;//from w w  w.  j  a v  a 2  s  .  c o m
    try {
        TelnetClient telnet = new TelnetClient();

        telnet.connect(url, Integer.parseInt(port));
        BufferedInputStream input = new BufferedInputStream(telnet.getInputStream());
        PrintStream output = new PrintStream(telnet.getOutputStream());

        readUntil("name:", input, null, url, port);
        write(user, output);
        readUntil("word:", input, null, url, port);
        sendPsw(output, psw);
        readUntil(">", input, null, url, port);

        response = issueCommand(poll, output, input, dnid, path, url, port);

        if (telnet.isConnected()) {
            telnet.disconnect();
        }
    } catch (IOException ex) {
        LOG.error("Error when communicating with Telnet", ex);
    } catch (NullPointerException ex) {
        throw new TelnetException(ex);
    }
    return response;
}

From source file:com.comcast.cats.telnet.TelnetConnection.java

/**
 * Creates a TelnetConnection insatnce.//ww  w  .j  a  v a 2 s. c om
 *
 * @param ip
 *            : of the telnet device
 * @param port
 *            : telnet port
 * @param defaultPromptString
 *            : default prompt string to be used. Usually ">".
 *
 */
public TelnetConnection(String host, Integer port, String defaultPromptString) {
    this.host = host;
    this.port = port;
    this.defaultPromptString = defaultPromptString;
    this.telnetClient = new TelnetClient();
    setDefaultReadTimeout(DEFAULT_READ_TIMEOUT);
    lastActiveTime = new Date();
}

From source file:io.vertx.ext.shell.term.TelnetTermServerTest.java

@Before
public void before() throws Exception {
    vertx = Vertx.vertx();/* ww  w.  j a va  2  s  .  c o m*/
    client = new TelnetClient();
    client.addOptionHandler(new EchoOptionHandler(false, false, true, true));
    client.addOptionHandler(new SimpleOptionHandler(0, false, false, true, true));
    client.addOptionHandler(new TerminalTypeOptionHandler("xterm-color", false, false, true, false));
}

From source file:br.com.anteros.sms.modem.IPModemDriver.java

@Override
protected void connectPort() throws GatewayException, IOException, InterruptedException {
    try {//  w w  w  .  ja  v  a2  s .c om
        Logger.getInstance().logInfo("Opening: " + this.ipAddress + " @" + this.ipPort, null,
                getGateway().getGatewayId());
        this.tc = new TelnetClient();
        this.tc.addOptionHandler(this.ttopt);
        this.tc.addOptionHandler(this.echoopt);
        this.tc.addOptionHandler(this.gaopt);
        if (getGateway().getIpProtocol() == IPProtocols.BINARY)
            this.tc.addOptionHandler(this.binaryopt); // Make telnet session binary, so ^Z in ATHander.Sendmessage is send raw!
        if (getGateway().getIpEncryption()) {
            try {
                this.tc.setSocketFactory(SSLContext.getInstance("Default").getSocketFactory());
            } catch (NoSuchAlgorithmException e) {
                Logger.getInstance().logError("Unable to find algorithm needed for using SSL", e,
                        getGateway().getGatewayId());
                // TODO: although not supposed to happen, something should be done if it does
            }
        }
        this.tc.connect(this.ipAddress, this.ipPort);
        this.in = this.tc.getInputStream();
        this.out = this.tc.getOutputStream();
        this.peeker = new Peeker();
    } catch (InvalidTelnetOptionException e) {
        throw new GatewayException("Unsupported telnet option for the selected IP connection.");
    }
}

From source file:com.dida.plugin.smslib.org.smslib.modem.IPModemDriver.java

@Override
protected void connectPort() throws GatewayException, IOException, InterruptedException {
    try {//from  ww  w . j  a  va 2 s .c o  m
        Logger.getInstance().logInfo("Opening: " + this.ipAddress + " @" + this.ipPort, null,
                getGateway().getGatewayId());
        this.tc = new TelnetClient();
        this.tc.addOptionHandler(this.ttopt);
        this.tc.addOptionHandler(this.echoopt);
        this.tc.addOptionHandler(this.gaopt);
        if (getGateway().getIpProtocol() == IPProtocols.BINARY) {
            this.tc.addOptionHandler(this.binaryopt); // Make telnet session binary, so ^Z in ATHander.Sendmessage is send raw!
        }
        if (getGateway().getIpEncryption()) {
            try {
                this.tc.setSocketFactory(SSLContext.getInstance("Default").getSocketFactory());
            } catch (NoSuchAlgorithmException e) {
                Logger.getInstance().logError("Unable to find algorithm needed for using SSL", e,
                        getGateway().getGatewayId());
                // TODO: although not supposed to happen, something should be done if it does
            }
        }
        this.tc.connect(this.ipAddress, this.ipPort);
        this.in = this.tc.getInputStream();
        this.out = this.tc.getOutputStream();
        this.peeker = new Peeker();
    } catch (InvalidTelnetOptionException e) {
        throw new GatewayException("Unsupported telnet option for the selected IP connection.");
    }
}

From source file:eu.geekgasm.kintrol.KinosKontroller.java

private void createTelnetClient() throws IOException, InvalidTelnetOptionException {
    telnetClient = 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);

    telnetClient.addOptionHandler(ttopt);
    telnetClient.addOptionHandler(echoopt);
    telnetClient.addOptionHandler(gaopt);
}

From source file:com.dangdang.ddframe.job.console.controller.RegistryCenterController.java

private boolean validate(final RegistryCenterConfiguration config) {

    String[] zkAddress = config.getZkAddressList().split(",");

    // //from   w w w .j a  v  a 2 s .co m
    TelnetClient client = new TelnetClient();
    String hostname;
    int port;
    for (String address : zkAddress) {
        try {
            hostname = address.substring(0, address.indexOf(":")).trim();
            port = Integer.parseInt(address.substring(address.lastIndexOf(":") + 1).trim());

            client.setDefaultTimeout(5000);
            client.connect(hostname, port);
            if (client.isConnected()) {
                return true;
            }
        } catch (Exception e1) {
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                //
            }
        }
    }
    return false;
}