List of usage examples for org.apache.commons.net.telnet TelnetClient disconnect
@Override public void disconnect() throws IOException
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 w ww. j a v a 2 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 {/* www. ja 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: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 {// w w w.ja va2 s. c om 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.WeatherTelnet.java
public static final void main(String[] args) { TelnetClient telnet; telnet = new TelnetClient(); try {/*from w w w . j a v a 2s. c o m*/ 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.openhab.binding.ddwrt.internal.DDWRTBinding.java
@Override protected void execute() { logger.trace("execute"); if (password == null) { return;// ww w.ja v a2 s. co m } else if (StringUtils.isBlank(password)) { logger.error("Password mustn't be empty!"); return; } try { TelnetClient client = null; for (DDWRTBindingProvider provider : providers) { for (String item : provider.getItemNames()) { String query = null; String type = provider.getType(item); if (queryMap.containsKey(type)) { if (type.startsWith(DDWRTBindingProvider.TYPE_ROUTER_TYPE)) { query = queryMap.get(type); } else if (type.startsWith(DDWRTBindingProvider.TYPE_WLAN_24) && !interface_24.isEmpty()) { query = queryMap.get(type) + " " + interface_24 + " | grep UP"; } else if (type.startsWith(DDWRTBindingProvider.TYPE_WLAN_50) && !interface_50.isEmpty()) { query = queryMap.get(type) + " " + interface_50 + " | grep UP"; } else if (type.startsWith(DDWRTBindingProvider.TYPE_WLAN_GUEST) && !interface_guest.isEmpty()) { query = queryMap.get(type) + " " + interface_guest + " | grep UP"; } } else { continue; } if (query == null) { continue; } logger.trace("execute query ({}) ({}) ({})", query, ip, username); if (client == null) { client = new TelnetClient(); client.connect(ip); if (username != null) { receive(client); send(client, username); } receive(client); send(client, password); receive(client); } send(client, query); String answer = receive(client); String[] lines = answer.split("\r\n"); if (lines.length >= 2) { answer = lines[1].trim(); } Class<? extends Item> itemType = provider.getItemType(item); State state = null; if (itemType.isAssignableFrom(SwitchItem.class)) { if (lines.length > 2) { if (lines[1].contains("UP")) { state = OnOffType.ON; } else { state = OnOffType.OFF; } } else { state = OnOffType.OFF; } } else if (itemType.isAssignableFrom(NumberItem.class)) { state = new DecimalType(answer); } else if (itemType.isAssignableFrom(StringItem.class)) { state = new StringType(answer); } if (state != null) { eventPublisher.postUpdate(item, state); } } } if (client != null) { client.disconnect(); } } catch (Exception e) { logger.warn("Could not get item state ", e); } }
From source file:org.openhab.binding.fritzbox.internal.FritzboxBinding.java
@Override protected void execute() { if (password == null) return;/* w w w. j a va2 s . c om*/ else if (password.trim().isEmpty()) return; try { TelnetClient client = null; for (FritzboxBindingProvider provider : providers) { for (String item : provider.getItemNames()) { String query = null; String type = provider.getType(item); if (queryMap.containsKey(type)) { query = queryMap.get(type); } else if (type.startsWith("tam")) { query = "ctlmgr_ctl r tam settings/" + type.toUpperCase() + "/Active"; } else if (type.startsWith("query")) { query = type.substring(type.indexOf(":") + 1).trim(); } else continue; if (client == null) { client = new TelnetClient(); client.connect(ip); if (username != null) { receive(client); send(client, username); } receive(client); send(client, password); receive(client); } send(client, query); String answer = receive(client); String[] lines = answer.split("\r\n"); if (lines.length >= 2) { answer = lines[1].trim(); } Class<? extends Item> itemType = provider.getItemType(item); org.openhab.core.types.State state = null; if (itemType.isAssignableFrom(SwitchItem.class)) { if (answer.equals("1")) state = OnOffType.ON; else state = OnOffType.OFF; } else if (itemType.isAssignableFrom(NumberItem.class)) { state = new DecimalType(answer); } else if (itemType.isAssignableFrom(StringItem.class)) { state = new StringType(answer); } if (state != null) eventPublisher.postUpdate(item, state); } } if (client != null) client.disconnect(); } catch (Exception e) { logger.warn("Could not get item state ", e); } }
From source file:org.openremote.controller.protocol.telnet.TelnetCommand.java
public void send(boolean readResponse) { TelnetClient tc = null; if (readResponse) { setResponse(""); }/*from www . j a v a2 s . c o m*/ 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); } } } }