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:adams.gui.tools.TelnetPanel.java

@Override
protected void initialize() {
    TerminalTypeOptionHandler ttopt;/*from w  w w .  j a va2s. c  om*/
    EchoOptionHandler echoopt;
    SuppressGAOptionHandler gaopt;

    super.initialize();

    m_Client = new TelnetClient();

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

    try {
        m_Client.addOptionHandler(ttopt);
        m_Client.addOptionHandler(echoopt);
        m_Client.addOptionHandler(gaopt);
    } catch (Exception e) {
        System.err.println("Error registering telnet option handlers:");
        e.printStackTrace();
    }

    m_CommandIndex = 0;
    m_CommandHistory = new ArrayList<String>();
    m_CommandHistory.add(""); // empty command to clear command text field
}

From source file:io.termd.core.telnet.TelnetClientRule.java

@Override
protected void before() throws Throwable {
    client = new TelnetClient() {
        @Override/*from  w  w w  . j  av a 2s.  c o m*/
        protected void _connectAction_() throws IOException {
            super._connectAction_();
            socket = _socket_;
            directOutput = _output_;
            setKeepAlive(false);
        }
    };
}

From source file:com.xebialabs.overthere.cifs.telnet.CifsTelnetConnection.java

@Override
public OverthereProcess startProcess(final CmdLine cmd) {
    checkNotNull(cmd, "Cannot execute null command line");
    checkArgument(cmd.getArguments().size() > 0, "Cannot execute empty command line");

    final String obfuscatedCmd = cmd.toCommandLine(os, true);
    logger.info("Starting command [{}] on [{}]", obfuscatedCmd, this);

    try {/*from ww w.  java2 s  .  c  o  m*/
        final TelnetClient tc = new TelnetClient();
        tc.setConnectTimeout(connectionTimeoutMillis);
        tc.addOptionHandler(new WindowSizeOptionHandler(299, 25, true, false, true, false));
        logger.info("Connecting to telnet://{}@{}", username, address);
        tc.connect(address, port);
        final InputStream stdout = tc.getInputStream();
        final OutputStream stdin = tc.getOutputStream();
        final PipedInputStream callersStdout = new PipedInputStream();
        final PipedOutputStream toCallersStdout = new PipedOutputStream(callersStdout);
        final ByteArrayOutputStream outputBuf = new ByteArrayOutputStream();
        final int[] exitValue = new int[1];
        exitValue[0] = -1;

        final Thread outputReaderThread = new Thread("Telnet output reader") {
            @Override
            public void run() {
                try {
                    receive(stdout, outputBuf, toCallersStdout, "ogin:");
                    send(stdin, username);

                    receive(stdout, outputBuf, toCallersStdout, "assword:");
                    send(stdin, password);

                    receive(stdout, outputBuf, toCallersStdout, ">", "ogon failure");
                    send(stdin, "PROMPT " + DETECTABLE_WINDOWS_PROMPT);
                    // We must wait for the prompt twice; the first time is an echo of the PROMPT command,
                    // the second is the actual prompt
                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);
                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);

                    if (workingDirectory != null) {
                        send(stdin, "CD /D " + workingDirectory.getPath());
                        receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);
                    }

                    send(stdin, cmd.toCommandLine(getHostOperatingSystem(), false));

                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);

                    send(stdin, "ECHO \"" + ERRORLEVEL_PREAMBLE + "%errorlevel%" + ERRORLEVEL_POSTAMBLE);
                    receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE);
                    receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE);
                    String outputBufStr = outputBuf.toString();
                    int preamblePos = outputBufStr.indexOf(ERRORLEVEL_PREAMBLE);
                    int postamblePos = outputBufStr.indexOf(ERRORLEVEL_POSTAMBLE);
                    if (preamblePos >= 0 && postamblePos >= 0) {
                        String errorlevelString = outputBufStr
                                .substring(preamblePos + ERRORLEVEL_PREAMBLE.length(), postamblePos);
                        logger.debug("Errorlevel string found: {}", errorlevelString);

                        try {
                            synchronized (exitValue) {
                                exitValue[0] = Integer.parseInt(errorlevelString);
                            }
                        } catch (NumberFormatException exc) {
                            logger.error("Cannot parse errorlevel in Windows output: " + outputBuf);
                        }
                    } else {
                        logger.error("Cannot find errorlevel in Windows output: " + outputBuf);
                    }
                } catch (IOException exc) {
                    throw new RuntimeIOException(format("Cannot start command [%s] on [%s]", obfuscatedCmd,
                            CifsTelnetConnection.this), exc);
                } finally {
                    closeQuietly(toCallersStdout);
                }
            }
        };
        outputReaderThread.setDaemon(true);
        outputReaderThread.start();

        return new OverthereProcess() {
            @Override
            public synchronized OutputStream getStdin() {
                return stdin;
            }

            @Override
            public synchronized InputStream getStdout() {
                return callersStdout;
            }

            @Override
            public synchronized InputStream getStderr() {
                return new ByteArrayInputStream(new byte[0]);
            }

            @Override
            public synchronized int waitFor() {
                if (!tc.isConnected()) {
                    return exitValue[0];
                }

                try {
                    try {
                        outputReaderThread.join();
                    } finally {
                        disconnect();
                    }
                    return exitValue[0];
                } catch (InterruptedException exc) {
                    throw new RuntimeIOException(format("Cannot start command [%s] on [%s]", obfuscatedCmd,
                            CifsTelnetConnection.this), exc);
                }
            }

            @Override
            public synchronized void destroy() {
                if (!tc.isConnected()) {
                    return;
                }

                disconnect();
            }

            private synchronized void disconnect() {
                try {
                    tc.disconnect();
                    logger.info("Disconnected from {}", CifsTelnetConnection.this);

                    closeQuietly(toCallersStdout);
                } catch (IOException exc) {
                    throw new RuntimeIOException(format("Cannot disconnect from %s", CifsTelnetConnection.this),
                            exc);
                }
            }

            @Override
            public synchronized int exitValue() {
                if (tc.isConnected()) {
                    throw new IllegalThreadStateException(
                            format("Process for command [%s] on %s is still running", obfuscatedCmd,
                                    CifsTelnetConnection.this));
                }

                synchronized (exitValue) {
                    return exitValue[0];
                }
            }
        };
    } catch (InvalidTelnetOptionException exc) {
        throw new RuntimeIOException(
                "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc);
    } catch (IOException exc) {
        throw new RuntimeIOException(
                "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc);
    }
}

From source file:com.xebialabs.overthere.telnet.TelnetConnection.java

@Override
public OverthereProcess startProcess(final CmdLine cmd) {
    checkNotNull(cmd, "Cannot execute null command line");
    checkArgument(cmd.getArguments().size() > 0, "Cannot execute empty command line");

    final String obfuscatedCmd = cmd.toCommandLine(os, true);
    logger.info("Starting command [{}] on [{}]", obfuscatedCmd, this);

    try {//w w w  . j a  v  a  2 s.  c o  m
        final TelnetClient tc = new TelnetClient();
        tc.setSocketFactory(mapper.socketFactory());
        tc.setConnectTimeout(connectionTimeoutMillis);
        tc.addOptionHandler(new WindowSizeOptionHandler(299, 25, true, false, true, false));
        logger.info("Connecting to telnet://{}@{}", username, address);
        tc.connect(address, port);
        tc.setSoTimeout(socketTimeoutMillis);
        final InputStream stdout = tc.getInputStream();
        final OutputStream stdin = tc.getOutputStream();
        final PipedInputStream callersStdout = new PipedInputStream();
        final PipedOutputStream toCallersStdout = new PipedOutputStream(callersStdout);
        final ByteArrayOutputStream outputBuf = new ByteArrayOutputStream();
        final int[] exitValue = new int[1];
        exitValue[0] = -1;

        final Thread outputReaderThread = new Thread("Telnet output reader") {
            @Override
            public void run() {
                try {
                    receive(stdout, outputBuf, toCallersStdout, "ogin:");
                    send(stdin, username);

                    receive(stdout, outputBuf, toCallersStdout, "assword:");
                    send(stdin, password);

                    receive(stdout, outputBuf, toCallersStdout, ">", "ogon failure");
                    send(stdin, "PROMPT " + DETECTABLE_WINDOWS_PROMPT);
                    // We must wait for the prompt twice; the first time is an echo of the PROMPT command,
                    // the second is the actual prompt
                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);
                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);

                    if (workingDirectory != null) {
                        send(stdin, "CD /D " + workingDirectory.getPath());
                        receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);
                    }

                    send(stdin, cmd.toCommandLine(os, false));

                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);

                    send(stdin, "ECHO \"" + ERRORLEVEL_PREAMBLE + "%errorlevel%" + ERRORLEVEL_POSTAMBLE);
                    receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE);
                    receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE);
                    String outputBufStr = outputBuf.toString();
                    int preamblePos = outputBufStr.indexOf(ERRORLEVEL_PREAMBLE);
                    int postamblePos = outputBufStr.indexOf(ERRORLEVEL_POSTAMBLE);
                    if (preamblePos >= 0 && postamblePos >= 0) {
                        String errorlevelString = outputBufStr
                                .substring(preamblePos + ERRORLEVEL_PREAMBLE.length(), postamblePos);
                        logger.debug("Errorlevel string found: {}", errorlevelString);

                        try {
                            synchronized (exitValue) {
                                exitValue[0] = Integer.parseInt(errorlevelString);
                            }
                        } catch (NumberFormatException exc) {
                            logger.error("Cannot parse errorlevel in Windows output: " + outputBuf);
                        }
                    } else {
                        logger.error("Cannot find errorlevel in Windows output: " + outputBuf);
                    }
                } catch (IOException exc) {
                    throw new RuntimeIOException(
                            format("Cannot start command [%s] on [%s]", obfuscatedCmd, TelnetConnection.this),
                            exc);
                } finally {
                    closeQuietly(toCallersStdout);
                }
            }
        };
        outputReaderThread.setDaemon(true);
        outputReaderThread.start();

        return new OverthereProcess() {
            @Override
            public synchronized OutputStream getStdin() {
                return stdin;
            }

            @Override
            public synchronized InputStream getStdout() {
                return callersStdout;
            }

            @Override
            public synchronized InputStream getStderr() {
                return new ByteArrayInputStream(new byte[0]);
            }

            @Override
            public synchronized int waitFor() {
                if (!tc.isConnected()) {
                    return exitValue[0];
                }

                try {
                    try {
                        outputReaderThread.join();
                    } finally {
                        disconnect();
                    }
                    return exitValue[0];
                } catch (InterruptedException exc) {
                    throw new RuntimeIOException(
                            format("Cannot start command [%s] on [%s]", obfuscatedCmd, TelnetConnection.this),
                            exc);
                }
            }

            @Override
            public synchronized void destroy() {
                if (!tc.isConnected()) {
                    return;
                }

                disconnect();
            }

            private synchronized void disconnect() {
                try {
                    tc.disconnect();
                    logger.info("Disconnected from {}", TelnetConnection.this);

                    closeQuietly(toCallersStdout);
                } catch (IOException exc) {
                    throw new RuntimeIOException(format("Cannot disconnect from %s", TelnetConnection.this),
                            exc);
                }
            }

            @Override
            public synchronized int exitValue() {
                if (tc.isConnected()) {
                    throw new IllegalThreadStateException(
                            format("Process for command [%s] on %s is still running", obfuscatedCmd,
                                    TelnetConnection.this));
                }

                synchronized (exitValue) {
                    return exitValue[0];
                }
            }
        };
    } catch (InvalidTelnetOptionException exc) {
        throw new RuntimeIOException(
                "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc);
    } catch (IOException exc) {
        throw new RuntimeIOException(
                "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc);
    }
}

From source file:com.symbian.driver.plugins.ftptelnet.TelnetProcess.java

public boolean connectTelnet() {
    if (isTelnetConnected()) {
        return true;
    }/*from  w w  w. j a  va 2  s .  c om*/
    // Connect to FTP
    iClient = new TelnetClient();

    try {
        iClient.connect(iIP, iPort);
        LOGGER.info("Telnet connection established with transport : " + iIP + ":" + iPort);
    } catch (Exception lException) {
        LOGGER.log(Level.SEVERE, "Telnet Client: Failed to connect " + lException.getMessage());
        return false;
    }
    // connected
    // Get input and output stream references
    iInputStream = iClient.getInputStream();
    iOutputStream = new PrintStream(iClient.getOutputStream());

    // Advance to a prompt
    try {
        readUntilPrompt(iCommandTimeOut, false);
    } catch (Exception lException) {
        LOGGER.log(Level.SEVERE, "Failed to get prompt from Telnet Server");
        //disconnectTelnet();
        return false;
    }

    return true;
}

From source file:TelnetTest.java

public void testFTP_Telnet_Remote_Execution_003() throws IOException {
    os.write("testexecute\r\n".getBytes());
    os.flush();/*  w  w w .  ja va  2s.  c om*/

    //this shell will lock, open another one and kill TEF

    TelnetClient tc = new TelnetClient();
    tc.connect(telnetClient.getRemoteAddress());

    InputStream is2 = tc.getInputStream();
    OutputStream os2 = tc.getOutputStream();

    readUntil(is2, prompt);

    os2.write("ps | grep TestExecute\r\n".getBytes());
    os2.flush();

    String s = readUntil(is2, prompt);

    Pattern p = Pattern.compile(".*\\D+(\\d+)\\s[\\s:\\d]+TestExecute Script Engine.*",
            Pattern.DOTALL | Pattern.CASE_INSENSITIVE); //Pattern.DOTALL => '.' includes end of line
    Matcher m = p.matcher(s);

    assertTrue(m.matches());

    String s1 = m.group(1);

    int pid = Integer.parseInt(s1);

    os2.write(("kill " + pid + "\r\n").getBytes());
    os2.flush();
    readUntil(is2, prompt);
    os2.write("bye\r\n".getBytes());
    os2.flush();

    //we should be able now to close the other shell

    readUntil(is, prompt);

}

From source file:com.comcast.cats.service.power.WTI_NPS_1600_PowerDevice.java

@Override
public void createPowerDevConn() {
    client = new TelnetClient();

    client.setConnectTimeout(5000);//  ww  w  . ja va 2s  .c o m

    try {
        client.connect(host, port);
    } catch (SocketException socketException) {
        throw new UnableToCreatePowerControllerDevice(socketException);
    } catch (IOException ioException) {
        throw new UnableToCreatePowerControllerDevice(ioException);
    }
    in = client.getInputStream();

    out = client.getOutputStream();

    login();
}

From source file:com.kz.pipeCutter.MyTelnetClient.java

public TelnetClient getTelnetClient() {

    if (tc == null) {
        TelnetClient tc1 = 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 {//from  w w w .  j  av  a2  s .c  o  m
            tc1.addOptionHandler(ttopt);
            tc1.addOptionHandler(echoopt);
            tc1.addOptionHandler(gaopt);
        } catch (InvalidTelnetOptionException e) {
            System.err.println("Error registering option handlers: " + e.getMessage());
        }

        boolean end_loop = false;
        try {
            //tc1.setDefaultTimeout(4);
            tc1.connect(SmoothieUploader.smoothieIP, this.remotePort);
            tc1.registerNotifHandler(this);
            tc = tc1;
        } catch (IOException e) {
            System.err.println("Exception while connecting to: " + this.ipAddress + ":" + this.remotePort + "\n"
                    + e.getMessage());
        }

    }
    return tc;
}

From source file:expect4j.ExpectUtils.java

/**
 * TODO Simulate "Could not open connection to the host, on port...."
 * TODO Simulate "Connection refused"/*from  ww w  .  j av a2s.com*/
 */
public static Expect4j telnet(String hostname, int port) throws Exception {
    // This library has trouble with EOF
    final TelnetClient client = new TelnetClient();

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

    client.connect(hostname, port);
    InputStream is = new FromNetASCIIInputStream(client.getInputStream()); // null until client connected
    OutputStream os = new ToNetASCIIOutputStream(client.getOutputStream());

    StreamPair pair = new StreamPair(is, os) {
        public void close() {
            //super.close();
            try {
                if (client != null)
                    client.disconnect();
            } catch (IOException ioe) {

            }
        }
    };

    /*
    URL url=new URL("telnet", hostname, port, "",  new thor.net.URLStreamHandler());
    final URLConnection urlConnection=url.openConnection();
    urlConnection.connect();
    if (urlConnection instanceof TelnetURLConnection) {
    ((TelnetURLConnection)urlConnection).setTelnetTerminalHandler(new SimpleTelnetTerminalHandler());
    }
    OutputStream os=urlConnection.getOutputStream();
    InputStream is=urlConnection.getInputStream();
             
    StreamPair pair = new StreamPair(is, os) {
    public void close() {
        try { ((TelnetURLConnection)urlConnection).disconnect(); }catch(Exception e) { }
    }
    };
     */
    Expect4j expect4j = new Expect4j(pair);

    return expect4j;
}

From source file:de.quadrillenschule.azocamsyncd.ftpservice.FTPConnection.java

public String telnetCommands(String[] commands) {
    close();//w  ww. j  a va 2s. c o  m
    final TelnetClient telnetclient = new TelnetClient();
    telnetclient.setDefaultTimeout(TIMEOUT);
    try {
        telnetclient.connect(getLastWorkingConnection());

        final StringWriter sw = new StringWriter();
        for (String command : commands) {
            IOUtils.copy(new ByteArrayInputStream((command + "\r\n").getBytes(telnetclient.getCharset())),
                    telnetclient.getOutputStream());
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(FTPConnection.class.getName()).log(Level.SEVERE, null, ex);
        }

        // tins.join();
        telnetclient.disconnect();
        //  System.out.println(sw.toString());

        return null;//sw.toString();//sw.toString();

    } catch (IOException ex) {
        try {
            telnetclient.disconnect();
        } catch (IOException ex1) {
            Logger.getLogger(FTPConnection.class.getName()).log(Level.SEVERE, null, ex1);
        }
        Logger.getLogger(FTPConnection.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}