Ejemplo n.º 1
0
def login(telnetOb: Telnet):
    newL = '\n'.encode('ascii')
    telnetOb.open(var.addy, var.port)
    telnetOb.read_until(b'Login')
    telnetOb.write(var.user.encode('ascii') + newL)
    telnetOb.read_until(b'Password')
    telnetOb.write(var.passw.encode('ascii') + newL)
Ejemplo n.º 2
0
def attempt(host, port, timeout, outputFile, secondCall = False):
	try:
		tn = Telnet(host,port,timeout)
		tn.open(host,port,timeout)
		header = tn.read_some()
		tn.close()
		print "[!] Port %d seems to be open on %s" %(port,host)
		file = open(outputFile, 'a') #writes to file
		file.write("%s:%d"%(host,port))
		if header != "":
			file.write(" - %s"%(header))
		file.write("\n")
		file.close()
	except Exception, e:
		try:
			e[1]
			code, reason = e.args
			print "[ERROR] %s on %s:%d (%d)" %(reason,host,port,code)
		except IndexError:
			if e.args[0] == "timed out" and port in commonOpenPorts:
				if secondCall is False:
					print "[!] extending timeout on common port (%d)" %(port)
					return attempt(host, port, (timeout*2), outputFile, True)
			
			#only write timeouts to the file
			if e.args[0] == "timed out":
				file = open(outputTimeoutFile, 'a') #writes to file
				file.write("%s:%d"%(host,port))
				
				file.write("\n")
				file.close()
			print "[ERROR] %s on %s:%d " %(e.args[0],host,port)
Ejemplo n.º 3
0
def is_host_alive(host, port=None):
  """it checks whether a host is alive by connecting using Telnet
  Telnet is also necessary when a board behind a router.

  if a message of the exception is "Connection refused",
  it means that the host is alive, but telnet is not running on the port 'port'

  @param port: a port Telnet should connect to, default is None
  @type port: integer
  @return: result of check
  @rtype: boolean
  """
  CONNECTION_REFUSED = "Connection refused"
  telnet = Telnet()
  try:
    timeout_sec = 3
    print "is_host_alive: trying to connect by Telnet, host=%s, port=%s, timeout_sec=%s" % (host, port, timeout_sec)
    telnet.open(host, port, timeout_sec)
    telnet.close()
    return True
  except socket.error as exc:
    print exc
    if CONNECTION_REFUSED in str(exc):
      return True
    return False
Ejemplo n.º 4
0
def get_xml_data(hostname, timeout, node_failures, node_failure_threshold):
    xml_data = None

    try:
        t = Telnet()
        t.open(hostname, 8649, timeout)
    except socket.timeout:
        # currently only incrementing failure count for nodes that time out.
        # the other failures happen quickly enough to have little to no impact
        #  on total elapsed time, and thus aren't worthy worrying about
        ERR ("timeout connecting to host {0}. recording failure".format(hostname))
        node_failures[hostname] += 1
        WARN ("host {0} has failed {1} times - {2} more failures before removal from host list".format(hostname, node_failures[hostname], node_failure_threshold - node_failures[hostname]))
        return "node_failed"
    except socket.gaierror:
        ERR ("host not found: {0}".format(hostname))
    except socket.error:
        ERR ("could not connect to host - connection refused: {0}".format(hostname))
    else:
        D (1, "successfully connected to host {0}".format(hostname))
        try:
            xml_data = t.read_all()
        except:
            ERR ("couldn't read data from host {0}".format(hostname))
        else:
            D (3, "XML dump:\n{0}".format(xml_data))
            t.close()
            D (1, "connection to {0} closed".format(hostname))

    return xml_data
Ejemplo n.º 5
0
def main(host, port):
    telnet = Telnet()
    telnet.open(host, port)
    #Usually Telnet prompt starts with this, if the telnet service provide another
    #prompt, change it to that prompt
    telnet.read_until("login: "******"\n")
    #the note above also applies for this
    telnet.read_until("Password: "******"\n")
    #just omit this line if you want to just have the telnet command prompt,
    #or change it to what feel confortable with
    telnet.write("shell\n")
    reader = ReaderThread(telnet)
    reader.start()

    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    tty.setraw(fd)
    while 1:
        if not reader.isAlive(): break
        ch = sys.stdin.read(1)
        telnet.write(ch)
    telnet.close()
    termios.tcsetattr(fd, 1, old_settings)
Ejemplo n.º 6
0
def takeover_light(ip):
    t = Telnet()
    t.open(ip, 30000)
    t.write("[Link,Touchlink]")
    output = t.read_until("[Link,Touchlink,success", 10)
    print output
    t.close()
Ejemplo n.º 7
0
    def sendTo(self, hosts=None, default_port=1000, module=0, msg=None):
        """
        Send the message to the DEP.

        If the argument 'hosts' is an IP or a list of IP's, it iterate over them to have an answer.
        If the argument 'hosts' is an instance of DEPMessage, it uses the hosts known in the instance.
        Open a connection to the DEP, sends the message and return the answer
        in a synchronous manner.
        """
        if msg:
            self.message = msg
        self.module = module
        telnet = Telnet()
        # t.set_debuglevel(100)
        if isinstance(hosts, str):
            hosts = (hosts,)
        elif isinstance(hosts, DEPMessage):
            self._hosts = hosts._hosts
            hosts = self._hosts.keys()

        for host in hosts or self.hosts:
            try:
                if host in self._hosts and self._hosts[host]:
                    telnet = self._hosts[host]
                else:
                    logger.info('%s not active in %r', host, self._hosts)
                    if ':' in host:
                        telnet.open(*host.split(':'))
                    else:
                        telnet.open(host, default_port)
                    self._hosts[host] = telnet
                sock = telnet.get_socket()
                msg = self._build()
                bytessent = sock.send(msg)
                logger.debug('%d chars sent', bytessent)
                answer, size = b'', None
                while True:
                    answer += sock.recv(4096)
                    if not size and len(answer) >= 4:
                        size = int(codecs.encode(answer[:4][::-1], 'hex'), 16)
                    if len(answer) >= size:
                        break
                    readsel, _, _ = select([sock], [], [], 0.5)
                    if len(readsel) == 0:
                        answer += telnet.read_very_lazy()
                        break
                break
            except socket.error:
                telnet.close()
                self._hosts[host] = None
                logger.exception('Socket issue with %s', host)
                continue
        else:
            raise ValueError('No dep available in the list : ' +
                             str(hosts or self._hosts))
        self.current_answer = codecs.encode(answer, 'hex').decode().upper()
        if LOG_DEPCALLS:  # pragma: no cover
            with open('result.txt', 'ab') as out:
                out.write(b'>>' + codecs.encode(msg[13:], 'hex').upper() + b':' + self.current_answer.encode().upper() + b'\n')
        return self.current_answer
Ejemplo n.º 8
0
class DenonConnection(object):
    """POSTS commands to Denon API server"""
    def __init__(self, api_host, port, trigger_map):
        self._api_host = api_host
        self._port = port
        self._connection = None
        self.action_map = trigger_map

    def process_command_string(self, words, text):
        command = self.action_map.mapped_trigger(words, text)
        self.send(command)
        return command

    def connector(self):
        if self._connection is None or not self._connection.sock_avail():
            self._connection = Telnet()
            self._connection.open(self._api_host, self._port)
            time.sleep(4)
        return self._connection

    def send(self, command):
        if b"ZMON\r" in command:
            self.connector().write(b"ZMON\r")
            command = command.replace(b"ZMON\r", b"")
            time.sleep(7)
        self.connector().write(command)
Ejemplo n.º 9
0
class TelnetMonitor(Test):
    CONNECT_TIMEOUT = 60

    def __init__(self, case_id, params, ip, port):
        super(TelnetMonitor, self).__init__(case_id=case_id, params=params)
        self._ip = ip
        self._params = params
        self._guest_passwd = params.get('guest_passwd')
        self._port = port
        try:
            self._telnet_client = Telnet(host=self._ip, port=self._port)
        except EOFError:
            Test.test_error(
                self, 'Fail to connect to telnet server(%s:%s).' % (ip, port))
        self._telnet_client.open(self._ip,
                                 port=self._port,
                                 timeout=self.CONNECT_TIMEOUT)

    def close(self):
        Test.test_print(self,
                        'Closed the telnet(%s:%s).' % (self._ip, self._port))
        self._telnet_client.close()

    def __del__(self):
        Test.test_print(self,
                        'Closed the telnet(%s:%s).' % (self._ip, self._port))
        self._telnet_client.close()
Ejemplo n.º 10
0
def takeover_light(ip):
    t = Telnet()
    t.open(ip, 30000)
    t.write("[Link,Touchlink]")
    output = t.read_until("[Link,Touchlink,success", 10)
    print output
    t.close()
Ejemplo n.º 11
0
Archivo: Port.py Proyecto: flowsha/zhwh
 def lineprofile(self, params):
     try:
         echo = params[18].split("_")
         print("Telnet " + params[6])
         tn = Telnet()
         tn.open(params[6], 23, self.telnetTimeout)
         
         if "9800" in params[1]: tn.write("\n")
         print(tn.read_until(echo[0], self.cmdTimeout))
         tn.read_until("\xff\xfc\x03", 1)
         
         for i in [1,2,3,4,5,7,9,10,8]:
             if params[i+7] <> "":
                 tn.write(params[i+7] + "\n")
                 if i == 9 and "HW" in params[1]: print(tn.read_until(": ", self.cmdTimeout)),
                 print(tn.read_until(echo[i], self.cmdTimeout)),
                 
         print("\n\nBDID: %s" % params[0])
         print("Equipment Type: %s (%s)" % (params[1], params[6]))
         print("L112 Port: %s" % params[5])
         print("Equipment Port: %s/%s/%s" % (params[2], params[3], params[4]))
     except:
         print("Execute command fail.")
     finally:
         tn.close()
Ejemplo n.º 12
0
Archivo: Port.py Proyecto: flowsha/zhwh
 def show(self, params):
     try:
         echo = params[18].split("_")
         print("Telnet " + params[6])
         tn = Telnet()
         tn.open(params[6], 23, self.telnetTimeout)
         
         if "9800" in params[1]: tn.write("\n")
         print(tn.read_until(echo[0], self.cmdTimeout))
         tn.read_until("\xff\xfc\x03", 1)
         
         for i in range(1,7):
             if params[i+7] <> "":
                 tn.write(params[i+7] + "\n")
                 if "show board" in params[i+7]: tn.write(" ")
                 elif "slot" in params[i+7]:
                     print(tn.read_until("quit>", self.cmdTimeout)),
                     tn.write(" ")
                 elif "display" in params[i+7]:
                     print(tn.read_until(":", self.cmdTimeout)),
                     tn.write("\n   ")
                 print(tn.read_until(echo[i], self.cmdTimeout)),
         print("\n\nBDID: %s" % params[0])
         print("Equipment Type: %s (%s)" % (params[1], params[6]))
         print("L112 Port: %s" % params[5])
         print("Equipment Port: %s/%s/%s" % (params[2], params[3], params[4]))
     except:
         print("Execute command fail.")
     finally:
         tn.close()
Ejemplo n.º 13
0
def Switch(ip,user,password):

    try:
        tn = Telnet()
        tn.open(host=ip, port=23)
        response = 'Success'
        tn.write(user.encode('utf-8') + b"\n")
        if password:
            tn.read_until(b"Password: "******"\n")
    except:
        
        response = 'Failed'

    finally:
        print (response)
        tn.write(b"Terminal len 0\n")
        tn.write(b"sh inventory\n")
        tn.write(b"sh env all\n")       
        tn.write(b"sh version\n")
        tn.write(b"sh clock\n")
        tn.write(b"show vlan\n")
        tn.write(b"sh process cpu\n")
        tn.write(b"sh process memory\n")
        tn.write(b"sh logging\n")
        
        tn.write(b"ls\n")
        tn.write(b"exit\n")

        readoutput = tn.read_all().decode('utf-8')
        f = open ("Output.txt" , "w")
        f.write (readoutput) 
        f.close
Ejemplo n.º 14
0
def attempt(host, port, timeout, outputFile, secondCall=False):
    try:
        tn = Telnet(host, port, timeout)
        tn.open(host, port, timeout)
        header = tn.read_some()
        tn.close()
        print "[!] Port %d seems to be open on %s" % (port, host)
        file = open(outputFile, 'a')  #writes to file
        file.write("%s:%d" % (host, port))
        if header != "":
            file.write(" - %s" % (header))
        file.write("\n")
        file.close()
    except Exception, e:
        try:
            e[1]
            code, reason = e.args
            print "[ERROR] %s on %s:%d (%d)" % (reason, host, port, code)
        except IndexError:
            if e.args[0] == "timed out" and port in commonOpenPorts:
                if secondCall is False:
                    print "[!] extending timeout on common port (%d)" % (port)
                    return attempt(host, port, (timeout * 2), outputFile, True)

            #only write timeouts to the file
            if e.args[0] == "timed out":
                file = open(outputTimeoutFile, 'a')  #writes to file
                file.write("%s:%d" % (host, port))

                file.write("\n")
                file.close()
            print "[ERROR] %s on %s:%d " % (e.args[0], host, port)
Ejemplo n.º 15
0
def test_connect(ip, port, timeout=5):
    tn = Telnet()
    try:
        tn.open(ip, port, timeout=timeout)
        return True
    except (socket.timeout, socket.error, socket.gaierror):
        print('\nCannot connect IP:%s port:%s\n' % (ip, port))
        return False
Ejemplo n.º 16
0
 def open(self, *args, **kwargs):
     """
     Works exactly like the Telnet.open() call from the telnetlib
     module, except SSL/TLS may be transparently negotiated.
     """
     Telnet.open(self, *args, **kwargs)
     if self.force_ssl:
         self._start_tls()
Ejemplo n.º 17
0
class TelnetDriver(Driver):
    """Represents a connection with Telnet"""
    def __init__(self,
                 target,
                 username='',
                 password='',
                 port=23,
                 username_finder='username: '******'password: '******'' or self.password != '':
            self.expect(self.username_finder)
            self.send_text(self.username)
            self.expect(self.password_finder)
            self.send_text(self.password)

    def send_text(self, text):
        try:
            self._client.write(text.encode('ascii'))
            return True
        except socket.error:
            raise DriverError("Connection closed while sending text")

    def read_until(self, text, timeout=2):
        try:
            return self._client.read_until(text.encode('ascii'), timeout)
        except EOFError:
            raise DriverError("Connection closed without receiving EOF")

    def read_eof(self, timeout=2):
        return self._client.read_all()

    def expect(self, expr_list, timeout=2):
        try:
            return self._client.expect(expr_list, timeout)
        except EOFError:
            raise DriverError(
                "EOF was reached without finding the expected text")

    def close(self):
        self._client.close()
Ejemplo n.º 18
0
def do_telnet(ip,port):
    server = Telnet()
    try:
        server.open(ip,port,timeout=4)
        return True
    except Exception as e:
        return False
    finally:
        server.close() 
Ejemplo n.º 19
0
def test_connect(host, port, timeout=5):
    """测试主机地址及端口是否可用"""
    client = Telnet()
    try:
        client.open(host, port, timeout=timeout)
        return True
    except:
        print('Cannot connect IP:{} port:{}'.format(host, port))
        return False
Ejemplo n.º 20
0
 def checkTelnet():
     try:
         Telnet.open(
             self.host_device_input.text(), '23',
             timeout=3)  ## Timeout to prevent large hang times
     except:
         return f'PASSED: Telnet Disabled on {self.host_device_input.text()}'
     else:
         Telnet.close()
         return f'FAILED: Telnet Enabled on {self.host_device_input.text()}'
Ejemplo n.º 21
0
class TelnetConnection(object):
    connection = None
    message_count = 0

    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.connection = Telnet()
        self.connect()


    def connect(self):
        while True:
            try:
                self.connection.open(self.host, self.port,
                                     timeout=TELNET_CONNECTION_TIMEOUT)
                logging.info('Telnet connected to %s:%s' % (
                                                        self.host, self.port))
                break
            except socket.error as e:
                logging.error('Telnet connect to %s:%s error: %s' % (
                                                    self.host, self.port, e))
                gevent.sleep(TELNET_RECONNECT_TIMEOUT)
                continue
        handle = gevent.spawn(self.handle)
        pool.add(handle)


    def handle(self):
        while True:
            try:
                line = self.connection.read_until('\r\n',
                                                  timeout=TELNET_READ_TIMEOUT)
                line = line.strip()
                logging.info('Got from %s:%s: %s (%s)' % (self.host, self.port, line, self.message_count))
                self.message_count += 1
                continue

            except EOFError as e:
                logging.error('Telnet read %s:%s error: %s' % (
                                                    self.host, self.port, e))
                self.connect()

            except Exception as e:
                if e.message == 'timed out':
                    pass

    def send(self, msg):
        try:
            self.connection.write('%s\r\n' % msg)
        except socket.error as e:
            logging.error('Cannot send to %s:%s: %s' % (
                                                    self.host, self.port, e))
            self.connection.close()
            self.connect()
Ejemplo n.º 22
0
def connection_telnet(hostname, port, sstring, timeout):
    """
    Connects to a socket, checks for the WELCOME-MSG and closes the
    connection.
    Returns nothing.
    
    """
    connection = Telnet()
    connection.open(hostname, port)
    connection.read_until(sstring, timeout)
    connection.close()
Ejemplo n.º 23
0
def runTELNET (ip,port):

    session = Telnet()

    try:
        session.open(ip, port)
        session.close()
        return "PASSED"

    except Exception as e:
        session.close()
        return e
Ejemplo n.º 24
0
Archivo: hydra.py Proyecto: dpep/hydra
class TelnetHacker(Hacker):
    @staticmethod
    def getServiceName():
        return 'telnet'

    def init(self):
        self.server = args.server
        self.client = Telnet()

    def attempt(self, login, password):
        if args.verbose:
            msg = '%s / %s  @  %s' % (login, password, self.server)
            self.log(msg)
        if args.debug:
            return False

        try:
            self.client.open(self.server, port=args.port, timeout=args.timeout)
            self.client.read_until('login: '******'Password: '******'"%s"' % msg
            if 'incorrect' in msg:
                return False

            # double check that we're in fact logged in
            cmd = 'echo $?'
            self.client.write(cmd + "\n")
            time.sleep(.1)
            msg = self.client.read_eager()
            if not msg.startswith(cmd):
                raise Exception('unexpected response: ' + msg)
            print '"%s"' % msg
            msg = msg[len(cmd):].strip(" \r\n")
            print '"%s"' % msg
            if not msg:
                # or did we timeout?
                return False

            if msg[0] in ['0', '1']:
                return True

            if msg[-1] in ['0', '1']:
                return True

        finally:
            self.client.close()
Ejemplo n.º 25
0
 def _getCellAlarm(self):
     '''Get CDMA alarms from omp server by telnet.
     '''
     alarms = ""
     tn = Telnet()
     try:
         #tn.set_debuglevel(1)
         tn.open(self.fwHost, self.fwPort, 10)
         tn.set_option_negotiation_callback(self._process_iac)
         tn.read_until("Login: "******"\r\n")
         tn.read_until("Password: "******"\r\n")
         tn.read_until("Please select the resource : ", 5)
         tn.set_option_negotiation_callback(None)
         tn.write("1\n")
         tn.read_until("login: "******"\n")
         tn.read_until("Password: "******"\n")
         result = tn.read_until("> ", 5)
         if "New Password:"******"\n")
             tn.read_until(": ", 5)
             tn.write(passwd + "\n")
             tn.read_until("> ", 5)
             
             self.ompOldPasswd = self.ompPasswd
             self.ompPasswd = passwd
             self.config.set("omp", "omp_passwd", self.ompPasswd)
             self.config.set("omp", "omp_passwd_old", self.ompOldPasswd)
             fp = open(self.confile, "r+")
             self.config.write(fp)
             fp.close()
             self._writelog("change new password successfully.")
         elif "Login incorrect" in result:
             self._reloadPassword()
             return alarms
         
         tn.write("TICLI\n")
         tn.read_until("> ", 5)
         tn.write("op:alarm 13\n")
         alarms = tn.read_until("COMPLETE", 5)
         tn.close()
     except:
         tn.close()
         self._writelog("get CDMA alarms fail.")
     finally:
         tn.close()
         return alarms
Ejemplo n.º 26
0
def telnet_exec(host, cmds, timeout=2):
    try:
        telnet = Telnet()
        host, port = host
        #telnet.debuglevel = 1
        telnet.open(host, port)
        #
        for item in cmds:
            telnet.write(item.encode() + b'\x0d\x0a')
            sleep(timeout)
            #
        else: telnet.close()
        #
    except Exception as msg: print show_except(msg)
Ejemplo n.º 27
0
def main(host, port):
    telnet = Telnet()
    telnet.open(host, port)

    reader = ReaderThread(telnet)
    reader.start()

    while 1:
        if not reader.isAlive(): break
        line = raw_input()
        telnet.write(line + '\n')
        time.sleep(0.3)

    telnet.close()
Ejemplo n.º 28
0
    def service_is_up(self, host):
        # FIXME(nmg): this implemention is too ugly, maybe has a elegant way. 
        telnet = Telnet()
        try:
            telnet.open(str(host.host), int(host.port))
        except socket.error:
            return False
        except error:
            raise

        finally:
            telnet.close()

        return True
Ejemplo n.º 29
0
    def service_is_up(self, host):
        # FIXME(nmg): this implemention is too ugly, maybe has a elegant way.
        telnet = Telnet()
        try:
            telnet.open(str(host.host), int(host.port))
        except socket.error:
            return False
        except error:
            raise

        finally:
            telnet.close()

        return True
Ejemplo n.º 30
0
def main(host, port):
    telnet = Telnet()
    telnet.open(host, port)

    reader = ReaderThread(telnet)
    reader.start()

    while 1:
       if not reader.isAlive(): break
       line = raw_input()
       telnet.write(line+'\n')
       time.sleep(0.3)

    telnet.close()
Ejemplo n.º 31
0
class Client:

    __slots__ = ("reader", "telnet", "uid")

    def __init__(self, callback=None, uid=None):
        self.uid = uid
        host = "localhost"
        port = 8080
        self.telnet = Telnet()
        self.telnet.open(host, port)
        self.reader = ReaderThread(self.telnet, callback, uid)
        self.reader.start()

    def send_input(self, line):
        self.telnet.write(line + "\n")
Ejemplo n.º 32
0
def main(host, port):
    telnet = Telnet()
    telnet.open(host, port)

    reader = ReaderThread(telnet)
    reader.start()

    while True:
        if not reader.isAlive():
            print 'giving up'
            break
        try:
            line = raw_input()
        except:
            break
        telnet.write(line + '\r\n')
    print '\n'
    os._exit(0)
Ejemplo n.º 33
0
def main(host, port):
    telnet = Telnet()
    telnet.open(host, port)

    reader = ReaderThread(telnet)
    reader.start()

    while 1:
        if not reader.isAlive():
            print 'giving up'
            break
        try:
            line = raw_input()
        except:
            break
        telnet.write(line + '\r\n')
    print '\n'
    os._exit(0)
Ejemplo n.º 34
0
def bofh(host="bofh.jeffballard.us", port=666, timeout=180, secondcall=False):
    try:
        tn = Telnet(host, port, timeout)
        tn.open(host, port, timeout)
        header = tn.read_all()
        new_header = header[161:]
        print(new_header)
        tn.close()
        print("[!] Port %d seems to be open on %s" % (port, host))

    except Exception as e:
        try:
            code, reason = e.args
            print("[ERROR] %s on %s:%d (%d)" % (reason, host, port, code))
        except IndexError:
            if e.args[0] == "timed out" and port in port:
                if secondcall is False:
                    print("[!] extending timeout on common port (%d)" % port)
Ejemplo n.º 35
0
def connect():
    server = 'localhost'
    port = 4212
    timeout = 5
    password = "******"
    global telnet
    telnet = Telnet()
    telnet.open(server, port, timeout)

    result = telnet.expect([r"VLC media player ([\d.]+)".encode("utf-8")])

    telnet.read_until("Password: "******"utf-8"))
    telnet.write(password.encode("utf-8"))
    telnet.write("\n".encode("utf-8"))

    result = telnet.expect(["Password: "******"utf-8"), ">".encode("utf-8")])

    if "Welcome" in str(result[2]):
        print("Connection Succesful")
Ejemplo n.º 36
0
def main():
    tn = Telnet()
    tn.open('10.100.218.8', 23, 3)

    ret = tn.read_until('username:'******'admin' + '\n')

    ret = tn.read_until('password:'******'admin' + '\n')

    ret = tn.read_until('>')
    print ret
    tn.write('show vlan')

    time.sleep(2)
    ret = tn.read_very_eager()
    print ret

    tn.close()
Ejemplo n.º 37
0
    def _send_command(self, torrent):
        telnet = Telnet()
        try:
            telnet.open(self.host, int(self.port))
        except socket.error:
            raise TorrentServerConnectException

        try:
            telnet.read_until(">")
            telnet.write("auth %s %s\n" % (str(self.username), str(self.passwd)))
            telnet.read_until(">")
            telnet.write("dllink %s\n" % str(torrent))
            telnet.write("quit\n")
            session = telnet.read_all()
            if "Bad login" in session:
                raise TorrentAuthException
            elif "exception" in session:
                raise TorrentURLException
        finally:
            telnet.close()
Ejemplo n.º 38
0
def main(host, port, filename):
	telnet = Telnet()
	telnet.open(host, port)
	reader = ReaderThread(telnet, filename)
	reader.start()
	while 1:
		if not reader.isAlive(): break
		try: 
			line = raw_input()
		except EOFError as exc:
			# If KeyboardInterrupt is not raised in 50ms, it's a real EOF event.
			telnet.write('\003\n')
			raise
		if line.find('break') >= 0 :
			# 서버로 Ctrl-C 를 보내어서 현재 진행 중인 작업을 중지시킨다.
			telnet.write('\003\n')
		else :
			telnet.write(line+'\n')
		time.sleep(0.3)
	telnet.close()
Ejemplo n.º 39
0
def main(host, port):

    Loaddxcc6()
    LoadWorkedGrids()
    LoadConfirmedStates()
    LoadAllFFMAGrids()

    telnet = Telnet()
    telnet.open(host, port)

    reader = ReaderThread(telnet)
    reader.start()
    telnet.write("N4LR\n")
    telnet.write("set/filter dxbm/pass 6\n")
    telnet.write("set/ve7cc\n")
    telnet.write("set/skimmer\n")

    while 1:
        # read a line and parse
        if not reader.isAlive(): break
    telnet.close()
    def _get_telnet_prompt(self, port, maxwait=30):
        ''' checks, if localhost:PORT is reachable via telnet during MAXWAIT
        seconds. returns the found cli prompt.
        If no telnet connection is reachable during MAXWAIT seconds,
        return value is 'unknown' is returned '''

        a_connection = Telnet()
        duration = 0
        prompt = None
        connected = False
        while (duration < maxwait) and not connected:
            duration += 1
            self._logger.debug('check telnet loop {}, will wait till {}'.format(duration, maxwait))
            try:
                a_connection.open('localhost', port, 10)
                prompt = a_connection.read_until( '>'.encode() )
                a_connection.close()
                connected = True
            except IOError:
                # connection not established - we will sleep for 1 second
                sleep(1)

        return prompt
Ejemplo n.º 41
0
def _check_local_port(port: int) -> bool:
    """
    check if the local port is in use
    Args:
        port (int): port

    Return:
        return True if the local port is valid, otherwise False

    Examples:
        >>> assert _check_local_port(5000)

    """
    # 1. extract host & port
    tn = Telnet()

    # 2. test host:port with socket
    res = True
    try:
        tn.open('127.0.0.1', port=port, timeout=3)
    except socket.error:
        res = False

    return res
Ejemplo n.º 42
0
class TelnetShell(AbstractRemoteShell):
    def __init__(self,
                 hostname,
                 username,
                 password=None,
                 port=23,
                 *args,
                 **kwargs):
        super(TelnetShell, self).__init__(hostname, *args, **kwargs)
        self._prompt = self._id
        self._hostname = hostname
        self._username = username
        self._password = password
        self._port = port
        self._telnet = Telnet()
        self._is_connected = False
        self._buffer = ""
        self.connect()

    def do_connect(self):
        self._telnet.open(self._hostname, self._port)
        self._read_until("login: "******"\n")
        if self._password:
            self._read_until("Password: "******"\n")
        sleep(.1)

        self._write("export PS1='%s'\n" % self._prompt)
        self._read_until(self._prompt)
        self._read_until(self._prompt)
        self._write("export COLUMNS=1024\n")
        self._read_until(self._prompt)
        self._write("stty columns 1027\n")
        self._read_until(self._prompt)

    def do_disconnect(self):
        self._telnet.close()

    def _write(self, text):
        self.log_spy_write(text)
        self._telnet.write(text.encode('utf-8'))

    def _read_until(self, marker):
        out = self._telnet.read_until(marker.encode('utf-8'))
        self.log_spy_read(out)
        return out

    def readline(self):
        (index, _, line) = self._telnet.expect(["\n", self._prompt])
        self.log_spy_read(line.decode('utf-8').rstrip("\n\r"))
        if index == 0:
            return line
        return None

    def execute_command(self,
                        command,
                        env={},
                        wait=True,
                        check_err=False,
                        cwd=None):
        wrapped_command = PrefixedStreamReader.wrap_command(command, env, cwd)
        self._write(wrapped_command + "\n")
        queue = Queue()
        PrefixedStreamReader(self, queue)
        return ShellResult(self, command, queue, wait, check_err)

    def do_reboot(self):
        self._write("reboot\n")
Ejemplo n.º 43
0
from telnetlib import Telnet

client = Telnet()
client.open('alt.org')

print client.read_until('=>')

client.write('l') # Login
client.write('barbershopper' + '\n') # Username
client.write('thisisabadpassword' + '\n') # Password
client.write('p') # Play
client.write('y' + '\n') # Don't randomize for me

## Setup character
#client.write('b') # Barberian
#client.write('o') # Orc
#client.write('f') # Female


print repr(client.read_until('=>'))
print repr(client.read_until('=>'))
print repr(client.read_until('=>'))
print repr(client.read_until('=>'))

Ejemplo n.º 44
0
from telnetlib import Telnet
import time
import sys
import os

sock = Telnet()
rsock = Telnet()

EMAddress="10.0.202.97"
EMPW="adept"
EMPort=7171

# Telnet to the EM ARCL port

try:
  sock.open(EMAddress, EMPort)
  print "Waiting for password prompt\n"
  buf = sock.read_until("Enter password:\r\n", 5)
  print "Entering password\n"
  sock.write("%s\n" %(EMPW))
  #sock.write("queuePickupDropoff PAVN-A02_1 FWIP-A02_W1-R1-C3\n")
  #time.sleep(10)
  #sock.write("quit\n")
  #sock.close()
  #print "Waiting for end of command listing\n"
  #sock.read_until("End of commands\r\n", 5)
except:
  print "Failed to connect"
  sys.exit()

#sock.close()
Ejemplo n.º 45
0
class TelnetShell(AbstractRemoteShell):

    def __init__(self, hostname, username, password=None, port=23, *args, **kwargs):
        super(TelnetShell, self).__init__(hostname, *args, **kwargs)
        self._prompt = self._id
        self._hostname = hostname
        self._username = username
        self._password = password
        self._port = port
        self._telnet = Telnet()
        self._is_connected = False
        self._buffer = ""
        self.connect()

    def do_connect(self):
        self._telnet.open(self._hostname, self._port)
        self._read_until("login: "******"\n")
        if self._password:
            self._read_until("Password: "******"\n")
        sleep(.1)

        self._write("export PS1='%s'\n" % self._prompt)
        self._read_until(self._prompt)
        self._read_until(self._prompt)
        self._write("export COLUMNS=1024\n")
        self._read_until(self._prompt)
        self._write("stty columns 1027\n")
        self._read_until(self._prompt)


    def do_disconnect(self):
        self._telnet.close()

    def _write(self, text):
        self.log_spy_write(text)
        self._telnet.write(text.encode('utf-8'))

    def _read_until(self, marker):
        out = self._telnet.read_until(marker.encode('utf-8'))
        self.log_spy_read(out)
        return out

    def readline(self):
        choices = [ "\n", self._prompt ]
        if version_info[0] > 2: choices = [ bytes(x, 'utf-8') for x in choices ]
        (index, _, line) = self._telnet.expect(choices)
        self.log_spy_read(line.decode('utf-8').rstrip("\n\r"))
        if index == 0:
            return line
        return None

    def execute_command(self, command, env={}, wait=True, check_err=False, cwd=None):
        wrapped_command = PrefixedStreamReader.wrap_command(command, env, cwd)
        self._write(wrapped_command + "\n")
        self.readline()
        sleep(.2)
        queue = Queue()
        PrefixedStreamReader(self, queue)
        return ShellResult(self, command, queue, wait, check_err)

    def do_reboot(self):
        self._write("reboot\n")
        sleep(.3)
Ejemplo n.º 46
0
    def processCmd(self, cmd):
        
        params = self.validParams(cmd)
        if params:
            try:
                '''
                get equipment command by params.
                '''
                conn = sqlite3.connect('bw.db')
                conn.text_factory = str
                cu = conn.cursor()
                sql = "select * from tb_equs where BDID='%s' and EQID='%s'"
                cu.execute(sql % (params['bdid'], params['eqid']))
                equ = cu.fetchone()
                
                if equ is None:
                    print("No such equipment.")
                    return False
            
                sql = "select CmdNo,CmdStr,CmdParams from tb_cmds where EQType='%s'"
                cu.execute(sql % equ[3])
                cmds = cu.fetchall()

                if cmds is None:
                    print("No such equipment type.")
                    return False
                
                sql = "select CmdQueue, Options from tb_virtual_cmds where EQType='%s' and VCmdStr='%s'"
                cu.execute(sql % (equ[3], params['cmd']))
                vcmds = cu.fetchone()
                conn.close()
                
                '''
                create equipment command list.
                '''
                frameId, slotId, portId = params['port'].split('-')
                cmd = []
                echoStr = equ[10].split('_')
                if echoStr[0] == 'r':
                    cmd.append(['\n', ''])
                    echoStr.remove(echoStr[0])
                
                cmd.append([equ[8], echoStr[0]])
                echoStr.remove(echoStr[0])
                cmd.append([equ[9], echoStr[0]])
                echoStr.remove(echoStr[0])
                
                cmdQueue = vcmds[0].split('_')
                cs = {}
                for c in cmds:
                    cs[c[0]] = [c[1], c[2]]
                for q in cmdQueue:
                    if cs[q][1] is not None:
                        p = cs[q][1].replace('f', frameId)
                        p = p.replace('s', slotId)
                        p = p.replace('p', portId)
                        p = p.replace('l', params['profile'])
                        p = p.split('+')
                        if len(p) == 3:
                            cmd.append([(cs[q][0] % (p[0], p[1], p[2])), '#'])
                        elif len(p) == 2:
                            cmd.append([(cs[q][0] % (p[0], p[1])), '#'])
                        if len(p) == 1:
                            cmd.append([(cs[q][0] % (p[0])), '#'])
                    else:
                        if echoStr[0] == '>' or echoStr[0] == ':':
                            cmd.append([cs[q][0], echoStr[0]])
                            echoStr.remove(echoStr[0])
                        else:
                            cmd.append([cs[q][0], '#'])
            except:
                print("Process command exception.")
                return False
            
            try:
                tn = Telnet()
                print("Telnet %s" % equ[5])
                tn.open(equ[5], 23, self.telnetTimeout)
            
                for c in cmd:
                    print(tn.read_until(c[1], self.cmdTimeout))
                    tn.read_until("\xff\xfc\x03", 0.1)
                    tn.write(c[0] + '\n')

                if vcmds[1] is not None:
                    ad = vcmds[1].split('_')
                    for a in ad:
                        if a == 's':
                            time.sleep(0.5)
                            tn.write(' ')
                        elif a == 'y':
                            tn.write('y\n')
                        elif a == 'r':
                            tn.write('\n')
                        elif a == "q":
                            print(tn.read_until("quit)", 20))
                            tn.write('\n')
                            print(tn.read_until("End", 20))
                        
                print(tn.read_until('#', self.cmdTimeout))
                tn.close()
                
                print("\nBDID: %s, BDName: %s" % (equ[0], self.bmcc(equ[1])))
                print("EQID: %s, EQType: %s, EQName: %s" % (equ[2], equ[3], self.bmcc(equ[4])))
                print("WIP: %s" % equ[5])
                print("MAC: %s" % equ[7])
                print("Address: %s" % self.bmcc(equ[11]))
                print("EqPort: %s" % params['port'])
            except:
                print("Running command timeout.")
                return False
Ejemplo n.º 47
0
class CArium_ECM(CLogger):
    '''
    ************************************************
    [Author]: [email protected]
    [Description]: This class will give support for ECM initialization, Connection
        and communication.
    [Methods]:    
    [History]:                                                                 
    ************************************************
    '''
    
    def __init__(self):
        CLogger.__init__(self)
        self.reset()

        
    def reset(self):
        self.str_VM_ip = ''
        self.int_Telnet_port = ''
        self.str_VM_user = ''
        self.str_VM_password = ''
        self.str_remote_desktop_file = ''
        self.obj_telnet_connection = None
        self.int_last_match_index = -1
        self.b_connected = False
        self.b_valid = False

        
    def from_xml(self, xmlnode_ECM):
        try:
            self.str_VM_ip = xmlnode_ECM.find('vm_ip_addr').text
            self.str_VM_user = xmlnode_ECM.find('vm_user').text
            self.str_VM_password = xmlnode_ECM.find('vm_password').text
            self.int_Telnet_port = int(xmlnode_ECM.find('telnet_port').text.lower().strip(), 10)
            self.str_remote_desktop_file = xmlnode_ECM.find('remote_desktop_file_full_path').text
        except:
            self.log('ERROR', 'Failed to parse information from XML node')
            return -1
        self.b_valid = True
        return 0

    
    def is_valid(self):
        return self.b_valid
    

    def _open_remote_desktop(self):
        self.log('INFO', 'Opening remote desktop')
        str_cmd_mstsc = 'mstsc'
        list_cmd_connect_remote_destop = [str_cmd_mstsc, '/v', self.str_VM_ip]
        thread_remote_desktop = Thread(target=subprocess.Popen, args = [list_cmd_connect_remote_destop,])
        thread_remote_desktop.setDaemon(True)
        thread_remote_desktop.start()
    

    def _connect_telnet(self):
        self.log('INFO', 'Trying to connect to Telnet(%s:%s)' % \
                        (self.str_VM_ip, self.int_Telnet_port))
        try:
            self.obj_telnet_connection = Telnet(self.str_VM_ip, self.int_Telnet_port, 60)
            self.obj_telnet_connection.read_until('>', 2)
            self.obj_telnet_connection.write('viewpoint=0\r\n')
            self.obj_telnet_connection.read_until('>', 2)
        except:
            self.obj_telnet_connection = None
            return -1
        self.log('INFO', 'Connected to Telnet(%s:%s)' % \
                        (self.str_VM_ip, self.int_Telnet_port))
        return 0
    

    def connect(self):
        self.log('INFO', 'Checking if Source Point is alive')
        int_result = ping(self.str_VM_ip)
        if int_result == 0:
            if self._connect_telnet() == 0:
                self.log('INFO','Source Point is alive')
                self.b_connected = True
                return 0
        else:
            self.log('INFO', 'Source point is not alive')

        self.log('INFO', 'Trying to start Sourcepoint.')
        self._open_remote_desktop()
        
        start = time.clock()
        b_action_success = False
        while(time.clock() - start < 180):
            if self._connect_telnet() == 0:
                b_action_success = True
                break
            time.sleep(3)

        if b_action_success == False:
            self.log('ERROR', 'Failed to connect to SourcePoint via telnet')
            self.reset()
            return -1
        
        self.b_connected = True
        return 0


    def send_ecm_command(self, cmd):
        if cmd is None:
            raise Exception('Arium ECM-XDP3 command to send is None.')

        self.log('INFO', 'Sending ECM-XDP3 cmd: %s' % cmd.strip('\r\n'))
        
        if self.obj_telnet_connection == None:
            try:
                self.obj_telnet_connection.open(self.str_VM_ip, self.int_Telnet_port, 60)
            except:
                raise Exception('Failed to open connection to Arium server in VM.')

        #check if Arium server is alive.
        self.obj_telnet_connection.write(chr(13))
        resp=self.obj_telnet_connection.read_until('>', 2)
        if resp.find('>') is -1:
            raise Exception('FAIL', 'Arium server inactive. resp=%s'%resp)

        #send command to Arium Server.
        self.obj_telnet_connection.write(str(cmd))
        #usually ECM-XDP3 command will return in 120s.
        resp = self.obj_telnet_connection.read_until('>', 120)
        if resp.find('>') is -1:
            raise Exception('FAIL', 'Arium cli: no \'>\' after sending cmd.')

        str_running=r'Operation not valid while target is running'
        str_syntax_error=r'Syntax error:'
        str_no_target=r'Operation invalid without a target'
        str_no_link=r'No communications link established'
        str_mem_addr_exceed_limit='Memory address exceeds limit'

        if resp.find(str_running) is not -1:
            #fail; running command need halt first; halt may have failed.
            raise Exception('Target is running; %s.'%str_running)

        if resp.find(str_syntax_error) is not -1:
            #fail; syntax error; command is wrong.
            raise Exception('Arium command syntax error.')

        if resp.find(str_no_target) is not -1:
            #fail; no target; need to check connection to target platform.
            raise Exception('FAIL', 'ECM-XDP3 find no target; emulator connection error.')
        if resp.find(str_no_link) is not -1:
            #fail; no link; need to check connection to target platform.
            raise Exception('FAIL', 'No communications link established.')
        if resp.find(str_mem_addr_exceed_limit) is not -1:
            raise Exception('FAIL', 'Memory address exceeds limit.')
 

        self.log('INFO', 'Command %s sent; resp=%s' \
                            % (str(cmd).strip('\r\n '), resp.strip('\r\n> ')))

        return resp.strip('\r\n> ')

    
    def disconnect(self):
        if not self.b_connected:
            return 0
        self.log('INFO', 'Disconnect ECM')
        self.reset()
        return 0

    
    def is_connected(self):
        return self.b_connected & self.b_valid


    def msr(self, offset, write=None, halt_first=True):
        '''
        msr access using Arium ECM-XDP3.
        offset: msr offset; int or long.
        write: None if to read;
               32bit/64bit data if to write.
        halt_first: if it is True, halt before accessing msr;
                    if it is False, assuming system is already halted before
                        this function is called.
                    This is to enable multiple ECM operation in one halt.
        raise Exception in case of failure;
        return nothing if write succeed;
        return valid reading in int or long if read succeed;

        '''
        self.log('INFO', 'Accessing msr %x via ECM.'%offset)
        #assume ECM-XDP3 connection is valid.
        if self.is_connected() is False:
            errmsg='ECM connection not ready. '
            errmsg+='Please call validat_ecm() before any Arium operation.'
            raise Exception(errmsg)

        if halt_first is True:
            #halt before accessing msr
            self.halt()

        #read/write
        msr_reading=-1
        cmd='msr(%xh)'%offset

        if write is not None:
            #write msr
            cmd+=' = %x'%write

        cmd += '\r'

        resp=self.send_ecm_command(cmd)

        if halt_first is True:
            self.go()

        if write is None:
            msr_reading=int(resp.strip('\r\nH '), 16)
            return msr_reading


    def mem(self, addr, data=None, halt_first=True):
        '''
        mem access using Arium ECM-XDP3.
        addr: 32bit/64bit memory address; int or long.
        data: None if to read;
                   32bit data if to write.

        halt_first: if it is True, halt before accessing msr;
                    if it is False, assuming system is already halted before
                        this function is called.
                    This is to enable multiple ECM operation in one halt.
        raise Exception with error msg in string in case of failure;
        return nothing if write succeed;
        return valid reading in int or long if read succeed;

        '''
        self.log('INFO', 'Accessing memory %x via Arium'%addr)
        #assume ECM-XDP3 connection is valid.
        if self.is_connected() is False:
            errmsg='ECM connection not ready. '
            errmsg+='Please call validate_ecm() before any Arium operation.'
            raise Exception(errmsg)

        if halt_first is True:
            #halt before accessing memory
            self.halt()

        #read/write
        ret_data=-1
        #p is for physical address.
        cmd='ord4 %xp'%addr

        if data is not None:
            #write memory
            cmd+=' = %x'%data

        cmd += '\r'

        resp=self.send_ecm_command(cmd)
        
        if halt_first is True:
            self.go()

        if data is None:
            ret_data=int(resp.strip('\r\nH '), 16)
            return ret_data


    def port(self, addr, data=None, length=32, halt_first=True):
        '''
        I/O port access using Arium ECM-XDP3.
        addr: 8bit/16bit/32bit io port;int.
        data: None if to read;
                   data whose length is 'length' if to write.

        halt_first: if it is True, halt before accessing msr;
                    if it is False, assuming system is already halted before
                        this function is called.
                    This is to enable multiple ECM operation in one halt.
        return error message in string in case of failure;
        return valid reading in read succeed;
        return 0 if write succeed.

        '''

        self.log('INFO', 'Accessing port %x via ECM.'%addr)
        #assume ecm connection is valid.
        if self.is_connected() is False:
            errmsg='ECM connection not ready. '
            errmsg+='Please call validat_ecm() before any Arium operation.'
            raise Exception(errmsg)

        if halt_first is True:
            #halt before accessing io port
            self.halt()

        #if write, adaptive increase length according to length of data:
        if data > 0xffffffff:
            raise Exception('data length overflow: %x'%data)
        elif data.bit_length() > length:
            raise Exception('data (%x) is longer than given length(%d).' \
                             %(data, length))

        if length is 8:
            cmd='port'
        elif length is 16:
            cmd='wport'
        elif length is 32:
            cmd='dport'

        cmd+='(%x)'%addr

        if data is not None:
            #write to i/o port
            cmd+=' = %x'%data

        cmd += '\r'

        resp=self.send_ecm_command(cmd)

        if halt_first is True:
            self.go()

        if data is None:
            #return int reading for successful read.
            ret_data=int(resp.strip('\r\nH '), 16)
            return ret_data


    def halt(self):
        '''
        halt system using ECM-XDP3
        Exception will be raised if halt command failed.
        '''
        self.log('INFO', 'Halting system via ECM-XDP3.')
        resp=self.send_ecm_command('halt\r')


    def go(self):
        '''
        Resume system running state using ECM-XDP3
        Exception will be raised if go command failed.
        '''
        self.log('INFO', 'Resuming system running state via ECM-XDP3.')
        resp=self.send_ecm_command('go\r')
Ejemplo n.º 48
0
class ListenThread( threading.Thread ):
    """ 
    This class is the heart of the programm. It takes care of polling the Fritzbox
    and listening for calls being signalled.
    """ 
    
    def __init__(self, parent, debugIt=False):
        """ 
        This function initializes pynotify and staring the polling thread.
        """ 
        self.parent = parent
        self.logger = parent.logger
        self.debugIt = debugIt
        
        self.logger.debug("Fritzbox Listener started")

        # start polling
        self.telnet = Telnet()
        self.cancel_event = threading.Event()
        self.counter = 10
        self.running = False
        self.data_array = []
        
        threading.Thread.__init__(self)
    
    def run(self):
        """ 
        This function polls the Fritzbox and listens for calls being signalled.
        """ 
        
        while not self.cancel_event.isSet( ):
            if (self.debugIt): self.self.logger.debug("starting thread activities")

            if self.counter == 15:

                if (self.debugIt): self.logger.debug("testing connection")
                self.ping_ok = self.is_ping_ok_( )
                self.counter = 0

                # if connection present
                if self.ping_ok:
                    if (self.debugIt): self.logger.debug("connection present")
                    # if not running yet
                    if self.running == False:
                        self.logger.debug("connecting")

                        # try to connect to the Fritzbox
                        try:
                            self.telnet.open( IP, int(PORT) )
                            self.running = True

                            self.logger.debug("Connected to Fritz!Box")

                        except socket.error:
                            self.running = False
                            self.logger.error("ERROR: please check if you enabled the interior callerid of the\n\tFritzbox by calling #96*5* on your phone once and\n\tthat you are listening on the correct port")
                        except:
                            self.running = False
                            self.logger.error("ERROR: ", sys.exc_info( )[0])
                        
                # if no connection
                else:
                    self.logger.debug("no connection")
                    if self.running == True:
                        self.logger.debug("closing connection")
                        try:
                            self.telnet.close( )
                            self.running = False
                        except:
                            self.running = False
                            self.logger.error("ERROR: ", sys.exc_info( )[0])

                        self.logger.debug("Connection lost")

            self.counter = self.counter + 1
            
            if self.running == True:

                # poll the Fritzbox for new events
                if (self.debugIt): self.logger.debug("connected and reading data")
                try:
                    self.incomming_data = self.telnet.read_very_eager( )
                    self.data_array = string.split( self.incomming_data, ";" )
                except:
                    self.logger.error(sys.exc_info()[1])
 
                # if the returned data_array is filled with results, get active!
                if ( len( self.data_array ) >= 5 ):


                    # in case of an incomming call signal (RING)
                    if ( self.data_array[1] == "RING" ):

                        # check MSN
                        self.ignore = False
                        self.msn = self.data_array[4]
                        if (MSN=="*" or MSN.find(self.msn) >= 0):
                            self.logger.info("number %s reports some activity" % (self.msn))
                        else:
                            self.logger.info("number %s reports some activity - and will be ignored" % (self.msn))
                            self.ignore = True

                        if (not(self.ignore)):

                            self.logger.info("incoming phone call ..RING..RING..")
                            
                            
                            # if a telephone number is received with the call
                            if ( self.data_array[3] != "" ):

                                # search for alias name of person calling
                                self.logger.debug("searching for alias name of person calling")
                                self.phonenumber = self.data_array[3]
                                self.alias = get_name_( self.phonenumber, True )

                                self.logger.info('incoming phonecall from %s' % (self.alias))

                            # if no telephone number is received with the call
                            else:
                                self.logger.info("phonecall from an unknown person")
                                self.phonenumber = 'unknown'
                                self.alias = 'unknown'
                            
                            self.parent.raiseEvent("Fritzbox.incomingCall", self.phonenumber, self.alias, self.msn)
                            
                            # display popup message
                            #self.emit_notification_(_('incoming phonecall'), self.phonenumber, self.alias, self.msn)
                        
                            # save phonecall as unanswered in the call history
                            #calldate,calltime = self.data_array[0].strip( ).split( " " )
                            #self.save_calls_( "Callinfailed", calldate, calltime, self.phonenumber )
                        
                    # in case of an answered phonecall (CONNECT)
                    elif ( self.data_array[1] == "CONNECT" ):

                        # check MSN
                        self.ignore = False
                        self.msn = self.data_array[4]
                        if ((MSN == "*") or (MSN.find(self.msn) >= 0)):
                            self.logger.info("number %s reports some activity" % (self.msn))
                        else:
                            self.logger.info("number %s reports some activity - and will be ignored" % (self.msn))
                            self.ignore = True

                        if (not(self.ignore)):

                            self.logger.info("answered phonecall")

                    # in case of an outgoing phonecall (CALL)
                    elif ( self.data_array[1] == "CALL" ):

                        # check MSN
                        self.ignore = False
                        self.msn = self.data_array[4]
                        if ((MSN == "*") or (MSN.find(self.msn) >= 0)):
                            self.logger.info("number %s reports some activity" % (self.msn))
                        else:
                            self.logger.info("Inumber %s reports some activity - and will be ignored" % (self.msn))
                            self.ignore = True


                        if (not(self.ignore)):

                            self.logger.info("outgoing phonecall")

                            # if the called number does not start with a 0, add the city prefix
                            # to the number, to allow reverse lookup and unitary entries in the telephone book
                            if self.data_array[5][0] != '0':
                                self.phonenumber = CITY_PREFIX + self.data_array[5]
                            else:
                                self.phonenumber = self.data_array[5]

                            # search for alias name of person called
                            self.logger.debug("searching for alias name of person called")
                            self.alias = get_name_( self.phonenumber, True, "notification", self )

                            self.logger.info('outgoing phonecall to %s' % (self.alias))
                
                    # otherwise the signal means that a phonecall ended.
                    # else:
                    #    print _('INFO: phonecall terminated')

            time.sleep(1)


        # closing thread
        self.logger.debug("closing thread")
        self.telnet.close( )

        return

    
    def is_ping_ok_( self ):
        """ 
        This function checks the ping to the Fritzbox
        """

        # try to ping the Fritzbox
        if (self.debugIt): self.logger.debug('pinging the Fritzbox')
        self.lifeline = re.compile( r"(\d) received" )
        self.report = ( "0","1","2" )
        self.result = 0
        self.pingaling = os.popen( "ping -q -c2 -w2 "+IP,"r" )
        sys.stdout.flush( )

        while 1:
            self.line = self.pingaling.readline( )
            if not self.line: break
            self.igot = re.findall( self.lifeline,self.line )

            if self.igot:
                self.result = int( self.report[int( self.igot[0] )] )

        # ping failed        
        if self.result == 0:
            return False
        
        # ping successful
        else:
            return True
Ejemplo n.º 49
0
class CIM:

  def __init__(self):
	# The dict to use for tracking the outstanding jobs
	self.activeJobList = dict()
        self.longestCompletionTime = 0
        self.shortestCompletionTime = 0
        self.longestPendingTime = 0
        self.completionTimeTotal = 0
        self.pendingTimeTotal = 0
        self.averageCompletionTime = 0
        self.averagePendingTime = 0

	# number of jobs in replay list
	self.numReplayJobs = 0
        self.numSwaps = 0

	# list of replay jobs
	self.rawReplayJobList = []

        self.lastTime = 0;

	# counter for the current job in the replay list
        self.currentReplayJob = 0

	# number of active jobs
	self.numJobsActive = 0

        self.numJobsPending = 0

	# number of jobs issued regardless of completion status)
	self.numJobsIssued = 0

	# flag for whether the connection is established or not
	self.isConnected = 0

	# address for the EM
	self.emAddress = "10.0.202.97"
	#self.emAddress = "10.0.202.101"

	# ARCL port for EM
	self.emArclPort = 7171

        self.emArclPassword = "******";

	# Socked for ARCL communications
	self.sock = Telnet()

	# time last job was sent
	self.lastJobTime = 0

	# number of job commands issued
	self.numIssuedJobs = 0

	# number of jobs successfully completed
	self.numSuccessfulJobs = 0

	# number of jobs cancelled by CIM
	self.numCIMCancelledJobs = 0

	# number of interrupted jobs
	self.numInterruptedJobs = 0

	# number of failed jobs
	self.numFailedJobs = 0

	# buffer for incoming socket data
	self.oldSockData = ""

  # compares two times in the format HH:MM:SS and returns the number of seconds between former and latter
  def getInterval(self, lastTime, curTime):
    FMT = "%H:%M:%S"
    return dt.datetime.strptime(curTime, FMT) - dt.datetime.strptime(lastTime, FMT)

  # Routine to read in the jobs from the file
  # Should they all be read in at once? Or only as needed?
  def readJobs(self, filename):
	self.numReplayJobs = 0
	# need to measure the time between jobs.
	# Just set to fixed value for now
	lastJobTimeStamp = 0
	REPLAYLIST = open(replayFile)
        f = open(replayFile)
        jobs = f.readlines()
        f.close()
        FMT = '%H:%M:%S'
        lastDrop = ""
        for job in jobs: 
          job = job.strip()
          #job = "00:00:00 %s" % (job)
          (timestamp, type, pick, drop, pickpri, droppri, echo_string) = job.split(" ", 6)
          #interval = self.getInterval(self.lastTime, timestamp)
          #print "Interval is %s %s %s" %( timestamp, self.lastTime, interval)
          self.lastTime = timestamp
	  newJob = ReplayEntry()
	  self.numReplayJobs += 1
	  newJob.id = self.numReplayJobs
	  newJob.type = type
          currentTime = time.strptime(timestamp, FMT)
          if ( self.numReplayJobs == 1 ):
            newJob.interval = 0
          else:
            newJob.interval = time.mktime(currentTime) - time.mktime(lastJobTimeStamp)
            if ( newJob.interval < 0 ):
              newJob.interval += 24*60*60
          #newJob.interval = .5
          lastJobTimeStamp = currentTime
	  newJob.pickupGoal = pick
	  newJob.dropoffGoal = drop
          newJob.pickPri = pickpri
          newJob.dropPri = droppri
          newJob.echoStr = echo_string
          if ( pick == lastDrop ):
            self.numSwaps += 1
          lastDrop = drop
	  self.rawReplayJobList.append(newJob)
          log("Added job: %s %s %s %s %s" % (self.numReplayJobs, type, pick, drop, newJob.interval))
        log("Total jobs: %s Swaps: %s" % (self.numReplayJobs, self.numSwaps))

  # routine to clear old jobs.  This should be used at startup
  def clearQueue(self):
        # flush incoming buffer
        self.sock.read_lazy()
        log("Clearing EM queue")
        self.sock.write("queueshow\n")
        jobList = []
        queueIsClear = 0
        while ( queueIsClear == 0 ):
          buf = self.sock.read_until("\n", .1)
          buf = buf.rstrip()
          #log (buf)

          if ( buf == "EndQueueShow" ):
            queueIsClear = 1
            return

          ( first, rest ) = buf.split(" ", 1)
          if ( first == "QueueShow:" ):
            ( id, jobid, priority, status, rest ) = rest.split(" ", 4)
            if ( status == "Pending" or status == "InProgress" ):
              #self.sock.write("queuecancel jobid %s\n" % (jobid))
              self.sock.write("queuecancel id %s\n" % (id))
              log("Clearing job %s" % (id))
              time.sleep(.1)
          elif ( first == "QueueRobot:" ):
            ( robot, rest) = rest.split(" ", 1)
            log("Cancelling robot %s" % (robot))
            self.sock.write("queuecancel robotname %s\n" % (robot))


          


  # Routine to establish the 
  def initializeConnection(self):
  	try:
	  log("Initialzing CIM connection to EM %s:%s" % (self.emAddress, self.emArclPort))
	  self.sock.open(self.emAddress, self.emArclPort)
	  self.sock.read_until("Enter password:\r\n", 5)
	  self.sock.write("%s\n" % self.emArclPassword)
	  self.sock.read_until("End of commands\r\n")
          log ("EM connection initialized")

	except:
	  print "CIM connection failed - closing"
	  self.sock.close()

  # Routine to randomly query
  # Should this use a time interval?
  def queryCommand(self):
	print "query"

  # Routine to randomly cancel a job
  # Should this use a time rinterval?  Or a percentage of jobs?
  def cancelJob(self):
	print "cancel"

  # Any other random things that should happen?

  # Routine to send the next job
  def sendJob(self,job):
	log("Starting job %s %s %s" % (job.type, job.pickupGoal, job.dropoffGoal))
	self.sock.write("%s %s %s %s %s %s\n" % (job.type, job.pickupGoal, job.dropoffGoal, job.pickPri, job.dropPri, job.echoStr))
	self.lastJobTime = time.time()
	self.numJobsActive += 1
        self.numJobsIssued += 1
        self.numJobsPending += 1
        newJob = CIM_Command()
        newJob.pickupGoal = job.pickupGoal
        newJob.dropoffGoal = job.dropoffGoal
	newJob.startTime = time.time()
        newJob.status = "Pending"
        newJob.id = job.echoStr
	self.activeJobList[job.echoStr] = newJob

  # Routine for parsing the response
  def parseResponse(self,data):
	# read line.  Things we care about:
	#   		When a job is accepted and assigned a jobID
	#		When a job is assigned to a robot
	#		When a job is completed
	#		When a job fails
	#		When a job is interrupted
	#
	#  Responses of interest:
	#  		QueueUpdate
	#  		RobotUpdate
	# 
	
	lines = data.split("\n")
	for line in lines:
		line = line.rstrip()
                if ( line == "" or line == "\n" ):
                  continue

		# remove trailing CR/LF
		line = line.rstrip()

                # check for queueupdate
                #log("line is %s" % (line))
                ( type, rest ) = line.split(" ", 1)

                if ( type == "queuepickupdropoff" ):
                  #log (rest)
                  toks = rest.split(" ")
                  #job_id = toks[12]
                  job_id = toks[14]
                  # add the ID to the last job that was queued
                  #self.activeJobList[job_id] = self.activeJobList['LATEST']
                  #self.activeJobList[job_id].id = job_id
                  self.activeJobList[job_id].pickupID = toks[10]
                  self.activeJobList[job_id].dropoffID = toks[12]
                  #del self.activeJobList['LATEST']


                if ( type == "QueueUpdate:" ):
                  #log (rest)
                  ( id, jobid, priority, status, substatus, type, goal, robot, jdate, jtime, ignore1, ignore2 ) = rest.split(" ", 11)

                  # look through the list of jobs and see if the status update applies
		  for job in ( self.activeJobList.keys() ):
                        #log("Checking job %s %s" %(job, self.activeJobList[job].id))
                        if ( job == jobid and id == self.activeJobList[job].pickupID ):
                          #log("Job matches1, checking status")
                          self.activeJobList[job].pickupStatus = status
                          self.activeJobList[job].robotName = robot
                        elif ( job == jobid and id == self.activeJobList[job].dropoffID ):
                          #log("Job matches1, checking status")
                          self.activeJobList[job].dropoffStatus = status
                          self.activeJobList[job].robotName = robot

                        if ( ( self.activeJobList[job].pickupStatus == "InProgress" and 
                               self.activeJobList[job].status == "Pending" ) or
                             ( self.activeJobList[job].dropoffStatus == "InProgress" and
                               self.activeJobList[job].status == "Pending" )):
                          self.numJobsPending -= 1
                          self.activeJobList[job].status = "InProgress"
                          self.activeJobList[job].pickupStartTime = time.time()

                        if ( self.activeJobList[job].dropoffStatus == "Completed" and
                            self.activeJobList[job].status == "InProgress" ):
                          self.activeJobList[job].endTime = time.time()
                          self.numSuccessfulJobs += 1
                          totalTime = time.time() - self.activeJobList[job].startTime
                          pendingTime = self.activeJobList[job].pickupStartTime - self.activeJobList[job].startTime
                          if ( totalTime > self.longestCompletionTime ):
                            self.longestCompletionTime = totalTime
                          if ( self.shortestCompletionTime == 0 or totalTime < self.shortestCompletionTime ):
                            self.shortestCompletionTime = totalTime
                          if ( pendingTime > self.longestPendingTime ):
                            self.longestPendingTime = pendingTime
                          self.completionTimeTotal += totalTime
                          self.pendingTimeTotal += pendingTime
                          self.averageCompletionTime = self.completionTimeTotal / self.numSuccessfulJobs
                          self.averagePendingTime = self.pendingTimeTotal / self.numSuccessfulJobs
                          log("Job %s completed in %6.0f sec total %6.0f sec pending %6.0f sec operating" % (id, totalTime, pendingTime, totalTime - pendingTime))
                          del self.activeJobList[job]
                          self.numJobsActive -= 1
                          return

                        if ( job == jobid and ( status == "Failed" or status == "Interrupted" ) ):
                          self.numFailedJobs += 1
                          log("Job %s failed" % id)
                          #del self.activeJobList[job]
                          self.numJobsPending += 1 
                          self.activeJobList[job].status = "Pending"
                          return
Ejemplo n.º 50
0
import time
import sys
import os

sock = Telnet()

EMAddress="10.0.200.200"
EMPW="adept"
EMPort=7171

#print "Attempting to synchronize clock with EM %s\n" %(EMAddress)

# Telnet to the EM ARCL port

try:
  sock.open(EMAddress, EMPort)
  print "Waiting for password prompt\n"
  buf = sock.read_until("Enter password:\r\n", 5)
  print "Entering password\n"
  sock.write("%s\n" %(EMPW))
  #sock.write("queuePickupDropoff PAVN-A02_1 FWIP-A02_W1-R1-C3\n")
  #time.sleep(10)
  #sock.write("quit\n")
  #sock.close()
  #print "Waiting for end of command listing\n"
  #sock.read_until("End of commands\r\n", 5)
except:
  print "Failed to connect"
  sys.exit()

#sock.close()
Ejemplo n.º 51
0
class TelnetCommnuicate(CommunicateBase):
    def __init__(self, **kwargs):
        """
         :param kwargs: 可用参数['host', 'port', 'timeout]
         """
        self.dev = Telnet()
        self.settings = kwargs

    def apply_settings(self, **kwargs):
        self.settings = kwargs

    def connect(self):
        if self.alive():
            self.close()
        host, port, timeout = self.settings.get('ip'), self.settings.get(
            'port'), self.settings.get('timeout', 3)
        self.dev.open(host, int(port), int(timeout))

    def read_until(self, match, **kwargs):
        timeout = kwargs.get('timeout', 1)
        data = self.dev.read_until(match=match, timeout=timeout)
        return self._fix_data(data, fix=kwargs.get('fix', False))

    def read_line(self, timeout=1, **kwargs):
        data = self.read_until(match='\n', timeout=timeout, **kwargs)
        return self._fix_data(data, fix=kwargs.get('fix', False))

    def read_available(self, timeout=None, **kwargs):
        data = ''
        try:
            data = self.dev.read_very_eager()
        except Exception:
            pass
        return self._fix_data(data, fix=kwargs.get('fix', False))

    def write(self, data, **kwargs):
        self.dev.write(data)

    def write_line(self, data, linefeed='\r\n', **kwargs):
        self.dev.write(data + linefeed)

    @property
    def type(self):
        return 'telnet'

    def set_read_timeout(self, timeout):
        if self.alive():
            self.dev.timeout = float(timeout)

    def close(self):
        if self.alive():
            self.dev.close()

    def alive(self):
        try:
            alive = self.dev.fileno()
            self.dev.sock_avail()
        except Exception as e:
            alive = False
        return alive

    def __str__(self):
        return '{!s}'.format(self.dev)
Ejemplo n.º 52
0
class TelnetConsole(ConsoleInterface):
    def __init__(self, mtda):
        self.telnet = None
        self.host = "localhost"
        self.mtda = mtda
        self.port = 23
        self.opened = False
        self.delay = 5
        self.timeout = 10

    """ Configure this console from the provided configuration"""

    def configure(self, conf):
        self.mtda.debug(3, "console.telnet.configure()")

        if 'host' in conf:
            self.host = conf['host']
        if 'port' in conf:
            self.port = conf['port']
        if 'delay' in conf:
            self.delay = conf['delay']
        if 'timeout' in conf:
            self.timeout = conf['timeout']

    def probe(self):
        self.mtda.debug(3, "console.telnet.probe()")
        result = True
        self.mtda.debug(3, "console.telnet.probe(): %s" % str(result))
        return result

    def open(self):
        self.mtda.debug(3, "console.telnet.open()")

        result = self.opened
        if self.opened == False:
            try:
                self.telnet = Telnet()
                self.telnet.open(self.host, self.port, self.timeout)
                self.opened = True
                result = True
            except:
                result = False

        self.mtda.debug(3, "console.telnet.open(): %s" % str(result))
        return result

    def close(self):
        self.mtda.debug(3, "console.telnet.close()")

        if self.opened == True:
            self.opened = False
            self.telnet.get_socket().shutdown(socket.SHUT_WR)
            self.telnet.close()
            self.telnet = None
        result = (self.opened == False)

        self.mtda.debug(3, "console.telnet.close(): %s" % str(result))
        return result

    """ Return number of pending bytes to read"""

    def pending(self):
        self.mtda.debug(3, "console.telnet.pending()")

        if self.opened == True:
            result = self.telnet.sock_avail()
        else:
            result = False

        self.mtda.debug(3, "console.telnet.pending(): %s" % str(result))
        return result

    """ Read bytes from the console"""

    def read(self, n=1):
        self.mtda.debug(3, "console.telnet.read(n=%d)" % n)

        if self.opened == False:
            time_before_open = time.time()
            self.open()
            if self.opened == False:
                # make sure we do not return too quickly if we could not connect
                self.mtda.debug(4,
                                "console.telnet.read(): failed to connnect!")
                time_after_open = time.time()
                elapsed_time = time_after_open - time_before_open
                if elapsed_time < self.delay:
                    delay = self.delay - elapsed_time
                    self.mtda.debug(
                        4,
                        "console.telnet.read(): sleeping {0} seconds".format(
                            delay))
                    time.sleep(delay)

        data = bytearray()
        try:
            while n > 0 and self.opened == True:
                avail = self.telnet.read_some()
                data = data + avail
                n = n - len(avail)
        except socket.timeout:
            self.mtda.debug(2, "console.telnet.read(): timeout!")

        self.mtda.debug(3, "console.telnet.read(): %d bytes" % len(data))
        return data

    """ Write to the console"""

    def write(self, data):
        self.mtda.debug(3, "console.telnet.write()")

        if self.opened == True:
            result = self.telnet.write(data)
        else:
            self.mtda.debug(2, "console.telnet.write(): not connected!")
            result = None

        self.mtda.debug(3, "console.telnet.write(): %s" % str(result))
        return result
Ejemplo n.º 53
0
from telnetlib import Telnet
import re

dut = Telnet()
dut.open("1.1.1.1")
# match pattern for prompts
userPrompt=re.compile("[Uu]sername:")
passwordPrompt=re.compile("[Pp]assword:")
execPrompt= re.compile(".*>$")
#match username prompt and enter username
dut.expect([userPrompt])
dut.write("adtran\n")
# match password prompt and enter password
dut.expect([passwordPrompt])
dut.write("adtran\n")
#match basic prompt
dut.expect([execPrompt])
# enter commands
dut.write("show ntp status\n")
# match the basic prompt and read the output
out= dut.expect([execPrompt])
print out[2]
dut.write("show arp\n")
out= dut.expect([execPrompt])
print out[2]
dut.write("exit\n")
out= dut.expect([execPrompt])
print out[2]
dut.close()

Ejemplo n.º 54
0
		incorrect_password = telnet.read_until(b"Try again :", 30).decode("utf-8").rstrip().endswith("Try again :")
		if incorrect_password is not True:
			break

		j += 1
		if j >= len(words2):
			continue
		combination = words1[i]+"-"+words2[j]
		print(combination)

		telnet.write(combination.encode('ascii') + b"\n")

		incorrect_password = telnet.read_until(b"return later.", 30).decode("utf-8").rstrip().endswith("return later.")
		if incorrect_password is not True:
			break

		telnet.read_all()

		telnet.open(host=hostname, port=port)

		j += 1

	else:
		i += 1
		continue
	break

telnet.close()
print("Username:"******"Password:", combination)
Ejemplo n.º 55
0
            except ValueError:
                print_help()
    
    # Initialise notifications.
    pynotify.init('squeezebox-notify')
    notification = pynotify.Notification('Squeezebox Notify',
        'Connecting to %s' % (server if port == 9090 else ('%s:%i' % (server, port,))),
        '/home/mmm/kode/squeezebox-notify/resources/squeezebox.jpg')
    notification.show()
    
    # Compile a regex for player related notifications, which are identified by a MAC address and then some.
    player_pattern = re.compile('^(([0-9a-f]{2}%3A){5}[0-9a-f]{2}) (.+)')

    # Start telnet clients (one a as listener, another to fetch info).
    listener = Telnet()
    listener.open(server, port)
    fetcher = Telnet()
    fetcher.open(server, port)
    listener.write('listen 1\n')

    # Start listening for server notifications and process them.
    while True:
        # Get notification data.
        data = listener.read_until('\n')
        # Analyse notification.
        m = player_pattern.match(data)
        # If it looks like a player related notification, break it apart and find out what it's about.
        if m:
            # First, get info about the player.
            player = get_player_info(fetcher, m.group(1))
            # Then, notify.
Ejemplo n.º 56
0
class CAPC():
    
    def __init__(self, str_ip, int_port = 23, str_user = "******", str_pwd = "apc"):
        self.str_ip = str_ip
        while self.str_ip.find('.0')>-1:
            apc_debug_print(self.str_ip)
            self.str_ip = self.str_ip.replace('.0', '.')
        self.int_port = int_port
        self.str_user = str_user
        self.str_pwd = str_pwd
        try:
            self.obj_telnet = Telnet(self.str_ip, self.int_port)
        except:
            print '[ERROR][APC]: Failed to connect to the APC server'
            self.obj_telnet = None
        self.lock_occupied = Lock()
        self.list_control_menu = ['Device Manager', \
                            'Outlet Management', \
                            'Outlet Control/Configuration']
        self.list_control_index = ['1','2','1','','1']
        self.b_log = False
        self.str_log_file = ''
        self.str_log_mode = 'w'
        self.b_print = False
        self.int_find = -1
        
    def __del__(self):
        pass
    
    def back_to_root(self):
        int_try = 0
        while(1):
            self.send_command(KEY_ESC)
            str_result = self.read_until(PROMPT_INPUT, 3)
            if str_result.find('Control Console'):
                break
            else:
                int_try +=1
                if int_try > 100:
                    return False
        return True
    
    def connect(self):
        while(1):
            self.obj_telnet.open(self.str_ip, self.int_port)      
            self.send_command(KEY_ENTER)
            #self.read_until([PROMPT_INPUT, PROMPT_PSW, PROMPT_USER], 3)
            try:
                self.read_until([PROMPT_INPUT, PROMPT_PSW, PROMPT_USER], 3)
            except:
                continue
            break
        return True
    
    def send_command(self, str_command):
        self.obj_telnet.write(str_command)
    
    def read_until(self, list_wait, int_time_out = None):
        str_get = ''
        res = [-1, None, '']
        if str(type(list_wait)) == "<type 'str'>":
            res =  self.obj_telnet.read_until(list_wait, int_time_out)
            if not res.find(list_wait):
                str_get = ''
                self.int_find = -1
            str_get = res
            self.int_find = 1    
        elif str(type(list_wait)) == "<type 'list'>":
            res =  self.obj_telnet.expect(list_wait, int_time_out)
            self.int_find = res[0] + 1
            str_get = res[2]
        if self.b_log:
            if not os.path.isdir(self.str_log_file):
                while(1):
                    try:
                        f_log = open(self.str_log_file,self.str_log_mode)
                    except:
                        print '[WARNING][CAPC][READUNTIL]: can not open log file(%s)' %self.str_log_file
                        self.b_log = False
                        break
                    f_log.write(str_get)
                    break
        if self.b_print:
            print str_get
        return str_get
        
    def log_on(self, str_user = '******', str_psw = 'apc'):
        self.connect()
        self.send_command(KEY_ENTER)
        while(1):     
            try:
                self.read_until([PROMPT_INPUT, PROMPT_PSW, PROMPT_USER], 3)
            except:
                return False
            if self.int_find == 1:
                break
            elif self.int_find == 2:
                self.send_command(str_psw + KEY_ENTER)
            elif self.int_find == 3:
                self.send_command(str_user + KEY_ENTER)
            else:
                pass
        return True
    
    def power_cycle(self, list_port, int_delay):
        self.power_control(list_port, ACTION_IMMEDIATE_OFF)
        time.sleep(int_delay)
        self.power_control(list_port, ACTION_IMMEDIATE_ON)
    
    def power_control(self, list_port, int_action):
        if int_action < 1 or int_action > 6:
            self.disconnect()
            return False
        b_by_port_number = True
        for str_entry in list_port:
            if not str(str_entry).isdigit():
                b_by_port_number = False
        self.log_on()
        self.goto_control_page()
        if b_by_port_number == True:
            for str_entry in list_port:
                str_entry  = str(str_entry)
                self.send_command(str_entry + KEY_ENTER)
                self.read_until(PROMPT_INPUT, 3)
                self.send_command('1' + KEY_ENTER)
                self.read_until(PROMPT_INPUT, 3)
                self.send_command(str(int_action) + KEY_ENTER)
                self.read_until('<ENTER> to cancel :', 3)
                self.send_command('yes'+KEY_ENTER)
                self.read_until('continue...', 3)
                self.send_command(KEY_ENTER)
                self.send_command(KEY_ESC)
                self.read_until(PROMPT_INPUT, 3)
                self.send_command(KEY_ESC)
                self.read_until(PROMPT_INPUT, 3)
        else:
            b_find = False
            if str(type(list_port)) == "<type 'str'>":
                list_port = [list_port, '']
            for str_entry in list_port:
                if str_entry  == '':
                    continue
                self.send_command(KEY_ENTER)
                str_result = self.read_until(PROMPT_INPUT, 3)
                while(1):
                    str_menu_index = self.get_menu_index(str_result, str_entry)
                    if str_menu_index == '':
                        if b_find == False:
                            self.disconnect()
                            return False
                        else:
                            break
                    else:
                        b_find = True
                    self.send_command(str_menu_index + KEY_ENTER)
                    self.read_until(PROMPT_INPUT, 3)
                    self.send_command('1' + KEY_ENTER)
                    self.read_until(PROMPT_INPUT, 3)
                    self.send_command(str(int_action) + KEY_ENTER)
                    self.read_until('<ENTER> to cancel :', 3)
                    self.send_command('yes'+KEY_ENTER)
                    self.read_until('continue...', 3)
                    self.send_command(KEY_ENTER)
                    self.send_command(KEY_ESC)
                    self.read_until(PROMPT_INPUT, 3)
                    self.send_command(KEY_ESC)
                    self.read_until(PROMPT_INPUT, 3)
                    pos = str_result.find(str_entry)
                    str_result = str_result[pos+len(str_entry)+1:]
        return True   
                
    def goto_control_page(self):
        while(1):
            self.back_to_root()
            str_result = self.read_until(PROMPT_INPUT, 3)
            int_pos = 0
            for str_entry in self.list_control_menu:
                if str_result.find(str_entry):
                    break
            b_find = True
            while(int_pos < len(self.list_control_menu)):
                str_menu_index = self.get_menu_index(str_result, self.list_control_menu[int_pos])
                if str_menu_index == '':
                    b_find = False
                    break
                self.send_command(str_menu_index + KEY_ENTER)
                str_result = self.read_until(PROMPT_INPUT, 3)
                int_pos += 1
            if b_find == True:
                break
        pass
    
    def get_menu_index(self, str_page, str_menu):
        str_page = str_page.lower()
        str_menu = str_menu.lower()
        ## find position of str_menu in str_page
        if str_page.find(str_menu)== -1:
            return ''
        int_pos = str_page.index(str_menu)
        ## get out MenuIndes if find
        if int_pos:
            str_index = str_page[int_pos - 4 : int_pos]
            str_index = str_index.replace(" ", "")
            str_index = str_index.replace(")", "")
            str_index = str_index.replace("-", "")
            return str_index
        else:
            return ''  
    
    def disconnect(self):
        if self.obj_telnet != None:
            self.obj_telnet.close()
        
    def check_port_name(self, list_port, list_name):
        pass
    
    def set_log(self, b_log = True, str_log_file = '', b_append = True):
        self.b_log = b_log
        self.str_log_file = str_log_file
        if b_append == True:
            self.str_log_mode = 'a'
        else:
            self.str_log_mode = 'w'
        return 0
Ejemplo n.º 57
0
 def shell_connection(self):
     telnet_conn = Telnet.open(self.host, self.profile.telnet_port, 3)  #timeout is 3 seconds
     return telnet_conn
Ejemplo n.º 58
-1
def main(host, port):
        telnet = Telnet()
        telnet.open(host, port)
	#Usually Telnet prompt starts with this, if the telnet service provide another
	#prompt, change it to that prompt
	telnet.read_until("login: "******"\n")
	#the note above also applies for this
	telnet.read_until("Password: "******"\n")
	#just omit this line if you want to just have the telnet command prompt,
	#or change it to what feel confortable with
	telnet.write("shell\n")
        reader = ReaderThread(telnet)
        reader.start()

	fd = sys.stdin.fileno()
	old_settings = termios.tcgetattr(fd)
	tty.setraw(fd)
        while 1:
                if not reader.isAlive(): break
		ch = sys.stdin.read(1)
                telnet.write(ch)
        telnet.close()
	termios.tcsetattr(fd, 1, old_settings)