/** 关闭连接 */ public void distinct() { try { if (telnet != null && !telnet.isConnected()) telnet.disconnect(); } catch (IOException e) { e.printStackTrace(); } }
/** * Receive answer from FritzBox - careful! This blocks if there is no answer from FritzBox * * @param client the telnet client * @return */ private static String receive(TelnetClient client) { StringBuffer strBuffer; try { strBuffer = new StringBuffer(); byte[] buf = new byte[4096]; int len = 0; Thread.sleep(750L); while ((len = client.getInputStream().read(buf)) != 0) { strBuffer.append(new String(buf, 0, len)); Thread.sleep(750L); if (client.getInputStream().available() == 0) break; } return strBuffer.toString(); } catch (Exception e) { logger.warn("Could not receive data", e.toString()); } return null; }
@Override public void connect() { try { log.debug("Starting connection to telnet device"); if (loggedIn) { throw new IllegalStateException("Already connected"); } log.info(String.format("Connecting to telnet service at %s:%d", targetHost, targetPort)); client.setConnectTimeout(targetTimeout); client.connect(targetHost, targetPort); expector = new Expect(client.getInputStream(), client.getOutputStream(), executorService, log); expector.setDefaultTimeout(targetTimeout); expector.setThrowOnError(true); loggedIn = true; } catch (Exception e) { throw new InteractiveSpacesException( String.format( "Error while connecting to telnet service at %s:%d", targetHost, targetPort), e); } }
public AutomatedTelnetClient(String server, int port) throws SocketException, IOException { // Connect to the specified server telnet.connect(server, port); // Get input and output stream references in = telnet.getInputStream(); out = new PrintStream(telnet.getOutputStream()); logger.info("connected telnet client to {}:{}", server, port); }
@Override protected void execute() { try { TelnetClient client = new TelnetClient(); client.connect(ip); receive(client); sendLine(client, password); receive(client); 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; sendLine(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); } } client.disconnect(); } catch (Exception e) { logger.warn("Could not get item state", e.toString()); } }
private void closeConnection() throws IOException { logger.debug("closeConnection()"); m_eventBus.post(new StateChangeEvent(this, EventType.LOST_CONNECTION)); m_TelnetState = TelnetState.DISCONNECTED; m_LoginState = LoginState.NO; m_StokerState = StokerCmdState.UNKNOWN; if (m_ReaderThread != null) m_ReaderThread.interrupt(); if (m_Telnet .isConnected()) // this is to get around a null Pointer exception in the disconnect if the // stoker is lost m_Telnet.disconnect(); }
@Test(groups = "wso2.all", description = "Identifying and storing unsatisfied OSGI components") public void testOSGIUnsatisfiedComponents() throws Exception { telnet.connect(InetAddress.getLocalHost().getHostAddress(), telnetPort); telnet.setSoTimeout(10000); ArrayList<String> arr = retrieveUnsatisfiedComponentsList("ls"); for (int x = 0; x < arr.size(); x++) { unsatisfiedList.add(arrList.get(x).split("\t")[3]); log.info(unsatisfiedList.get(x)); } assertEquals( unsatisfiedList.size(), 0, "Unsatisfied components detected" + " in server startup. " + getString(unsatisfiedList)); }
private static void createTelnetSession(String command) throws IOException, InterruptedException { telnet.connect(ControlMain.getActiveBox().getDboxIp()); OutputStream ostream = telnet.getOutputStream(); Writer writer = new OutputStreamWriter(ostream); writer.write(ControlMain.getActiveBox().getLogin() + "\n"); writer.flush(); Thread.sleep(1000); writer.write(ControlMain.getActiveBox().getPassword() + "\n"); writer.flush(); Thread.sleep(1000); writer.write(command + "\n"); writer.flush(); closeTelnetSession(); }
private void disconnect() { try { telnet.disconnect(); } catch (IOException e) { log.error("Error occured while telnet disconnection " + e); } }
public void disconnect() { try { telnet.disconnect(); } catch (Exception e) { logger.error("error while disconnecting telnet client"); } }
private void writeInputCommand(String value) { out = new PrintStream(telnet.getOutputStream()); out.println(value); out.flush(); log.info(value); }
private void createConnection() throws IOException { logger.info("Creating Telnet connection."); m_Telnet = new TelnetClient(); String strStokerIP = StokerWebProperties.getInstance().getProperty(StokerWebConstants.PROPS_STOKER_IP_ADDRESS); String strStokerPort = StokerWebProperties.getInstance().getProperty(StokerWebConstants.PROPS_STOKER_PORT); int iStokerPort = new Integer(strStokerPort).intValue(); m_Telnet.connect(strStokerIP, iStokerPort); m_TelnetState = TelnetState.CONNECTED; if (m_ReaderThread != null) { logger.warn("Interrupting thread"); m_ReaderThread.interrupt(); } m_ReaderThread = new Thread() { @Override public void run() { streamReader(); } }; m_ReaderThread.start(); m_StreamToStoker = m_Telnet.getOutputStream(); int x = 0; while (m_LoginState == LoginState.NO) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if (x++ > 60) { if (m_LoginState == LoginState.NO) { logger.warn("Unable to connect or login, giving up"); stopInternal(); break; } } } }
/** * Send line via Telnet to FritzBox * * @param client the telnet client * @param data the data to send */ private static void sendLine(TelnetClient client, String data) { try { data += "\r\n"; client.getOutputStream().write(data.getBytes()); client.getOutputStream().flush(); } catch (IOException e) { logger.warn("Could not send data", e.toString()); } }
@Override public void run() { try { TelnetClient client = new TelnetClient(); client.connect(ip); int state = 0; if (command == OnOffType.ON) state = 1; String cmdString = null; if (commandMap.containsKey(type)) { cmdString = commandMap.get(type) + " " + state; } else if (type.startsWith("tam")) { cmdString = "ctlmgr_ctl w tam settings/" + type.toUpperCase() + "/Active " + state; } else if (type.startsWith("cmd")) { int on = type.indexOf("ON="); int off = type.indexOf("OFF="); if (state == 0) { cmdString = type.substring(off + 4, on < off ? type.length() : on); } else { cmdString = type.substring(on + 3, off < on ? type.length() : off); } cmdString = cmdString.trim(); } /* * This is a approach with receive/send in serial way. This * could be done via a sperate thread but for just sending one * command it is not necessary */ receive(client); // password: sendLine(client, password); receive(client); // welcome text sendLine(client, cmdString); Thread.sleep(1000L); // response not needed - may be interesting // for reading status client.disconnect(); } catch (Exception e) { logger.warn("Could not send command", e.toString()); } }
private void readResponse() throws IOException { InputStream in = telnet.getInputStream(); BufferedReader inBuff = new BufferedReader(new InputStreamReader(in, "UTF-8")); String inputLine; while ((inputLine = inBuff.readLine()) != null) if (inputLine.contains("Unsatisfied")) { // filtering Unsatisfied components arrList.add(inputLine); log.info(inputLine); } inBuff.close(); out.close(); }
public static void runReboot() throws IOException, InterruptedException { Logger.getLogger("SerBoxTelnet").info(ControlMain.getProperty("msg_reboot")); telnet.connect(ControlMain.getActiveBox().getDboxIp()); OutputStream ostream = telnet.getOutputStream(); Writer writer = new OutputStreamWriter(ostream); writer.write(ControlMain.getActiveBox().getLogin() + "\n"); writer.flush(); Thread.sleep(1000); writer.write(ControlMain.getActiveBox().getPassword() + "\n"); writer.flush(); Thread.sleep(1000); writer.write("killall sectionsd" + "\n"); writer.flush(); Thread.sleep(1000); writer.write("killall camd2" + "\n"); writer.flush(); Thread.sleep(1000); writer.write("killall timerd" + "\n"); writer.flush(); Thread.sleep(1000); writer.write("killall timerd" + "\n"); writer.flush(); Thread.sleep(1000); writer.write("killall zapit" + "\n"); writer.flush(); Thread.sleep(1000); writer.write("killall controld" + "\n"); writer.flush(); Thread.sleep(1000); writer.write("killall nhttpd" + "\n"); writer.flush(); Thread.sleep(1000); writer.write("sleep 3" + "\n"); writer.flush(); Thread.sleep(1000); writer.write("busybox -reboot" + "\n"); writer.flush(); Thread.sleep(1000); closeTelnetSession(); }
public static final void main(String[] args) { TelnetClient telnet; 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); }
/** * 登录到目标主机 * * @param ip * @param port * @param username * @param password */ public void login(String ip, int port, String username, String password) { try { if (osType) { asstpwd = "Password:"******"Login incorrect"; } else { asstpwd = "password:"******"Login Failed"; } telnet.connect(ip, port); in = telnet.getInputStream(); out = new PrintStream(telnet.getOutputStream()); readUntil("login:"******"登录失败"); } } catch (Exception e) { throw new RuntimeException(e); } }
@Override public void disconnect() { loggedIn = false; try { log.info("Disconnecting from teclnet client"); if (expector != null) { expector.close(); } } catch (Exception e) { log.warn("Error while closing telnet session", e); } finally { expector = null; } try { if (client != null) { client.disconnect(); } } catch (Exception e) { log.warn("Error while closing telnet session", e); } finally { client = null; } }
public boolean isConnected() { return telnet.isConnected(); }
private void streamReader() { m_StreamFromStoker = m_Telnet.getInputStream(); try { // BufferedReader reader = new BufferedReader(new InputStreamReader( // streamFromStoker)); StringBuilder sb = new StringBuilder(); String line = null; int intRead; int lastRead = 0; int doubleLastRead = 0; byte[] buff = new byte[1024]; int ret_read = 0; while (m_TelnetState == TelnetState.CONNECTED) { if (m_StreamFromStoker.available() <= 0) { sleep(100); continue; } // telnet.sendAYT(2000); ret_read = m_StreamFromStoker.read(buff); for (int i = 0; i < ret_read; i++) { intRead = buff[i]; if (intRead >= 32 && intRead < 127) { char c = (char) intRead; sb.append(c); } if (intRead == ' ' && lastRead == ':' && sb.toString().contains(StokerWebConstants.STOKER_PROMPT_LOGIN)) // login: { logger.info("found login string"); sendLoginSequence(); sb = new StringBuilder(); } if (intRead == ' ' && lastRead == ':' && sb.toString().contains(StokerWebConstants.STOKER_PROMPT_PASSWORD)) // password { logger.info("found password string"); sendPasswordSequence(); sb = new StringBuilder(); } if (intRead == ' ' && lastRead == '>' && doubleLastRead == 47 && sb.toString().contains("tini") && sb.toString().contains(" />")) { logger.info("found tini prompt"); m_LoginState = LoginState.YES; } if (intRead == 't' && lastRead == 'r' && sb.toString().contains(StokerWebConstants.STOKER_CONDITION_START)) // stoker: start { logger.info("Stoker Start response detected"); m_StokerState = StokerCmdState.STARTED; } if (intRead == 'p' && lastRead == 'o' && sb.toString().contains(StokerWebConstants.STOKER_CONDITION_STOP)) // stkcmd: stop { logger.info("Stoker stopped response detected"); m_StokerState = StokerCmdState.STOPPED; } if (intRead == 'd' && lastRead == 'e') // && sb.toString().contains("stkcmd: not started")) { logger.debug("String: " + sb.toString()); logger.info("Stoker not started response detected"); m_StokerState = StokerCmdState.STOPPED; } if (intRead == 10) // && m_StokerState == StokerCmdState.STARTED) { if (sb.length() > 0) { sb.append('\n'); try { // Not sure if I want this here. m_LastMessageTime = Calendar.getInstance().getTime(); logger.trace("last message time: " + m_LastMessageTime); addDataPoint(sb.toString()); // System.out.print("p"); m_StokerResponseState = StokerResponseState.TEMPS; } catch (InvalidDataPointException idp) { logger.warn("Invalid Data Point: [" + sb.toString() + "]"); } sb = new StringBuilder(); } } doubleLastRead = lastRead; lastRead = intRead; } // end for read } // end while CONNECTED } catch (Exception e) { logger.error("Exception while reading socket: " + e.getMessage()); StackTraceElement[] sta = e.getStackTrace(); for (int i = 0; i < sta.length; i++) { logger.error(sta[i]); } reconnect(); } logger.error("Reader exiting"); }
private void writeInputCommand(String value) throws UnsupportedEncodingException { out = new PrintStream(telnet.getOutputStream(), true, "UTF-8"); out.println(value); out.flush(); log.info(value); }
private static void closeTelnetSession() throws IOException, InterruptedException { Thread.sleep(2000); telnet.disconnect(); }