Пример #1
0
def np(*args, **kwargs):
    host = wc.config_get_plugin('foobar_host')
    port = wc.config_get_plugin('foobar_port')
    try:
        tn = Telnet(host, port, timeout=3)
    except Exception as error:
        wc.prnt(wc.current_buffer(),
                'Cannot connect to foobar: {}'.format(error))
        return wc.WEECHAT_RC_ERROR
    tn.expect([b'11'])
    rawline = tn.read_until(b'\n', timeout=3)
    tn.close()
    rawline = rawline.decode('utf-8').split('|||')
    status = int(rawline[0])
    if status == 2:
        npstring = 'NP: nothing'
    else:
        fields = {
            'albumartist': rawline[6],
            'album': rawline[7],
            'date': rawline[8],
            'title': rawline[11],
            'artist': rawline[12]
        }
        nptemplate = wc.config_get_plugin('format')
        npstring = Template(nptemplate).safe_substitute(fields).encode('utf-8')
    wc.command(wc.current_buffer(), '/me ' + npstring)
    return wc.WEECHAT_RC_OK
Пример #2
0
 def syncOld(self, file: MufFile, tc: Telnet):
     tc.write(programFinder.format(file.filename))
     mindex, match, _ = tc.expect(
         [programFinderRegex, programFinderTerminator])
     fn = None
     while match is not None and mindex != 1:
         if match.group(1) == file.transformedname:
             fn = match.group(1)
             break
         else:
             mindex, match, _ = tc.expect(
                 [programFinderRegex, programFinderTerminator])
     tc.write(programListCommand.format(fn))
     mindex = 0
     lines = []
     lastindex = 0
     while mindex != 1:
         mindex, match, _ = tc.expect(
             [programListMatch, programListTerminator])
         if mindex != 1:
             if int(math.group(2)) != lastindex + 1:
                 print("Hmm. There might be a problem.")
             else:
                 lastindex = int(match.group(1))
             lines.append(match.group(2))
Пример #3
0
def NASpowerdown(Nname,Nuser,Npass,Ncommand,Nport):
	from telnetlib import Telnet
	if Nname == "":
		return _("no Name")
	l=_("Connection Error")
	try:
		tn = Telnet(Nname, Nport, 5)
		l=""
		if Nuser != "":
			l = l + tn.expect(['ogin:','sername'],10)[2]
			l = l + tn.read_very_lazy()
			tn.write('%s\r' % Nuser)
		if Npass != "":
			l = l + tn.read_until('assword:',10)
			l = l + tn.read_very_lazy()
			tn.write('%s\r' % Npass)
		l = l + tn.expect(['#',">"],10)[2]
		l = l + tn.read_very_lazy()
		tn.write('%s\r' % Ncommand)
		l = l + tn.expect(['#',">"],20)[2]
		l = l + tn.read_very_lazy()
		if config.plugins.elektro.NASwait.value == True:
			tt = time() + 90
			l = l + "\n waiting...\n"
			while tt>time() and ping.doOne(Nname,1) != None:
				sleep(2)
		tn.write('exit\r')
		l = l + tn.expect(['#',">"],5)[2]
		l = l + tn.read_very_lazy()
		tn.close()
	finally:
		return l
Пример #4
0
def test_telnet_service_mock_add_credentials():
    with TelnetServiceMock("127.0.0.1", 8023,
                           scenario=TelnetScenario.GENERIC) as target:
        login = uuid.uuid4().hex.encode()
        password = uuid.uuid4().hex.encode()

        assert target.host == "127.0.0.1"
        assert target.port == 8023

        tn = Telnet(target.host, target.port, timeout=1.0)

        tn.expect([b"Login: "******"login: "******"\r\n")

        tn.expect([b"Password: "******"password"], 1.0)
        tn.write(password + b"\r\n")

        _, match_object, _ = tn.expect([b"Login incorrect"], 1.0)
        assert match_object

        target.add_credentials(login.decode(), password.decode())

        tn.expect([b"Login: "******"login: "******"\r\n")

        tn.expect([b"Password: "******"password"], 1.0)
        tn.write(password + b"\r\n")

        _, match_object, foo = tn.expect([login + b"@target:~\$"], 1.0)

        assert match_object, foo.decode()
        tn.close()
Пример #5
0
def NASpowerdown(Nname, Nuser, Npass, Ncommand, Nport):
    from telnetlib import Telnet
    if Nname == "":
        return _("no Name")
    l = _("Connection Error")
    try:
        tn = Telnet(Nname, Nport, 5)
        l = ""
        if Nuser != "":
            l = l + tn.expect(['ogin:', 'sername'], 10)[2]
            l = l + tn.read_very_lazy()
            tn.write('%s\r' % Nuser)
        if Npass != "":
            l = l + tn.read_until('assword:', 10)
            l = l + tn.read_very_lazy()
            tn.write('%s\r' % Npass)
        l = l + tn.expect(['#', ">"], 10)[2]
        l = l + tn.read_very_lazy()
        tn.write('%s\r' % Ncommand)
        l = l + tn.expect(['#', ">"], 20)[2]
        l = l + tn.read_very_lazy()
        if config.plugins.elektro.NASwait.value == True:
            tt = time() + 90
            l = l + "\n waiting...\n"
            while tt > time() and ping.doOne(Nname, 1) != None:
                sleep(2)
        tn.write('exit\r')
        l = l + tn.expect(['#', ">"], 5)[2]
        l = l + tn.read_very_lazy()
        tn.close()
    finally:
        return l
def _connect(config):
    """Boilerplate to connect to a conviron."""
    # Establish connection
    telnet = Telnet(config.get("Conviron", "Host"))
    response = telnet.expect([re.compile(b"login:"******"Initial response is: {0!s}".format(response[2].decode()))
    if response[0] < 0:  # No match found
        raise RuntimeError("Login prompt was not received")
    # Username
    payload = bytes(config.get("Conviron", "User") + "\n", encoding="UTF8")
    telnet.write(payload)
    response = telnet.expect([re.compile(b"Password:"******"Sent username: {0!s}".format(payload.decode()))
    LOG.debug("Received: {0!s}".format(response[2].decode()))
    if response[0] < 0:  # No match found
        raise RuntimeError("Password prompt was not received")
    # Password
    payload = bytes(config.get("Conviron", "Password") + "\n", encoding="UTF8")
    telnet.write(payload)
    response = telnet.expect([re.compile(b"#")], timeout=TIMEOUT)
    LOG.debug("Send password: {0!s}".format(payload.decode()))
    LOG.debug("Received: {}".format(response[2].decode()))
    if response[0] < 0:  # No match found
        raise RuntimeError("Shell prompt was not received")
    return telnet
Пример #7
0
    def _connect_login(self):
        telnet = Telnet(self.ip)
        response = telnet.expect([re.compile(b'login'), ], timeout=TIMEOUT)

        if response[0] < 0:
            raise RuntimeError("Login prompt not recieved")
        self.logger.debug("Intial response is: {0!s}".format(response[2].decode()))
        # we MUST wait a little bit before writing to ensure that the stream isnt being written to.
        time.sleep(0.1)
        payload = bytes(self.telnet_username + "\n", encoding="UTF8")
        telnet.write(payload)

        response = telnet.expect([re.compile(b"Password:"******"Sent username: {0!s}".format(payload.decode()))
        self.logger.debug("Received: {0!s}".format(response[2].decode()))
        if response[0] < 0:  # No match found
            raise RuntimeError("Password prompt was not received")
        # Password
        payload = bytes(self.telnet_password + "\n", encoding="UTF8")
        telnet.write(payload)

        response = telnet.expect([shell_re, ], timeout=TIMEOUT)
        self.logger.debug("Send password: {0!s}".format(payload.decode()))
        self.logger.debug("Received: {}".format(response[2].decode()))
        if response[0] < 0:  # No match found
            raise RuntimeError("Shell prompt was not received")
        return telnet
Пример #8
0
class Bras(object):
    """ Базовый класс для Брасов """

    def __init__(self, di):
        self.host = str(di["host"])
        self.user = str(di["user"])
        self.pwd = str(di["password"])
        self.tn = None
        self.clname = str(di["name"])
        self.greet = str(di["greetings"])

    def __login(self):
        """ Метод для авторизации на Брасе
            результат сохраняет в базовом классе """
        self.tn = Telnet(self.host, 23, 5)
        self.tn.get_socket().settimeout(TIMEOUT)
        res = self.tn.expect(["Username:"******"login:"******"\n")
        res = self.tn.expect(["Password:"******"\n")
        # > ma5200 and e120, # asr, $ lisg
        res = self.tn.expect([r">", r"#", r"\$"], 5)
        if res[0] == -1:
            self.tn.close()
            return False
        # we're in for sure
        self.prepare_cli()
        return True

    def write(self, string):
        """ Метод для ввода команды в телнет терминал """
        try:
            self.tn.read_very_eager()
            self.tn.write(string + "\n")
        except (EOFError, AttributeError, IOError):
            res = self.__login()
            if not res:
                return False
            self.tn.write(string + "\n")
        except:
            print_exc()
            print_stack()
            print("Exc in write bras")
            res = self.__login()
            if not res:
                return False
            self.tn.write(string + "\n")
        return True
Пример #9
0
 def send(self, tc: Telnet):
     let_be = False
     while True:
         if self.send_method == "name":
             tc.write("@prog {}\n".format(self.transformedname).encode())
         elif self.send_method == "id":
             tc.write("@prog {}\n".format(self.id).encode())
         elif self.send_method == "regname":
             print("Using regname:{0}".format(self.regname))
             tc.write("@prog {}\n".format(self.regname).encode())
         mindex, match, _ = tc.expect([ProgramId, ProgramId2], timeout=3)
         if match is not None:
             self.id = int(match.group(1))
             break
     tc.write("1 {} delete\n".format(self.length * 10).encode())
     tc.write("i\n".encode())
     counter = 0
     with open(self.filename) as fi:
         lines = fi.readlines()
         if len(lines[-1]) > 0:
             lines.append('')
         for i in lines:
             tc.write("{}".format(i).encode())
             #                sleep(0.05)
             counter += 1
             print("{: =4.2}%".format(100 * counter / len(lines)),
                   end='\r',
                   flush=True)
     print("\n", end="", flush=True)
     print("finished sending")
     while True:
         tc.write('.\n'.encode())
         index, m, _ = tc.expect(editorInsertExitMatch, timeout=5)
         if m is not None:
             break
     print("compiling program")
     while True:
         tc.write("c\n".encode())
         index, m, line = tc.expect(editorCompilerStringMatch, timeout=7)
         if index != None and index != 1:
             print("Message Recieved")
             print(line.decode("ascii"))
             let_be = True
         if m is not None:
             break
     print("quitting")
     while True:
         if let_be:
             tc.write("q\n".encode())
         else:
             tc.write("x\n".encode())
         index, m, _ = tc.expect(editorExitStringMatch, timeout=7)
         if m is not None:
             break
Пример #10
0
def grab_cfg(device_dict):
    hostname, port = device_dict['hostname'], device_dict['port']
    tn = Telnet(eve_ip, port)
    tn.write(('\r\n').encode('ascii'))
    tn.write(('term leng 0\n').encode('ascii'))
    tn.write(('show run\n').encode('ascii'))
    time.sleep(1)
    tn.expect([('!\r\nversion.*\r\n').encode('ascii')])
    data = tn.expect([('!\r\nend').encode('ascii')])[2]
    print('Data from {} grabbed'.format(hostname))
    save_cfg(hostname, data)
Пример #11
0
 def _show_run(self,get_switch,get_switch_property,get_switch_access):
  ### variable arrange
  switch_name = get_switch['name']
  network_inform = get_switch['ip']
  telnet_port = network_inform.split(':')[1]
  telnet_ip = network_inform.split(':')[0].split('/')[0]
  telnet_user = get_switch_access['account']
  telnet_pass = get_switch_access['password']
  telnet_enable = get_switch_access['enable']
  ### telnet open time out in second
  self.telnet_open_timeout = float(10)

  ### telnet open processing
  try:
   telnet_pointer =  Telnet(telnet_ip,telnet_port,self.telnet_open_timeout)
  except:
   msg="[ error : "+time.asctime()+" ] can't open the telnet, ip : "+telnet_ip+", port :"+telnet_port
   self.logging_msg(self.run_syslog,msg)
   sys.exit()


  ### telnet login processing
  try:
   line_result = telnet_pointer.expect(Arista_manage._login_pattern,self.telnet_open_timeout)[1]
  except:
   msg="[ error : "+time.asctime()+" ] can't 2read login pattern : "+str(Arista_manage._login_pattern)
   self.logging_msg(self.run_syslog,msg)
   sys.exit()

  if not line_result:
   sys.exit()


  ### insert account for login
  telnet_pointer.write(telnet_user+"\n")

  ### wait the password pattern
  try:
   telnet_pointer.expect(Arista_manage._passwd_pattern,self.telnet_open_timeout)
  except:
   msg="[ error : "+time.asctime()+" ] can't read login pattern : "+str(Arista_manage._passwd_pattern)
   self.logging_msg(self.run_syslog,msg)
   sys.exit()

  telnet_pointer.write(telnet_pass+"\n")
  print telnet_pointer.expect([switch_name+"\w*>"],self.telnet_open_timeout)
  telnet_pointer.write("enable1234\n")
  print telnet_pointer.expect(Arista_manage._passwd_pattern,self.telnet_open_timeout)
  telnet_pointer.write(telnet_enable+"\n")
  print telnet_pointer.expect([switch_name+"\w*#"],self.telnet_open_timeout)


  telnet_pointer.write("exit\n")
  telnet_pointer.read_all()

  telnet_pointer.close()
Пример #12
0
def test_telnet_service_mock_regexp_mock():
    with TelnetServiceMock("127.0.0.1", 8023,
                           scenario=TelnetScenario.GENERIC) as target:
        assert target.host == "127.0.0.1"
        assert target.port == 8023

        mock = target.get_command_mock(re.compile("\d\dscoo\d\d"))
        mock.return_value = "bee"
        assert isinstance(mock, MagicMock)

        tn = Telnet(target.host, target.port, timeout=1.0)

        tn.expect([b"Login: "******"login: "******"admin" + b"\r\n")

        tn.expect([b"Password: "******"password"], 1.0)
        tn.write(b"admin" + b"\r\n")

        tn.expect([b"admin@target:~\$"], 1.0)
        tn.write(b"12scoo34" + b"\r\n")
        _, match_object, _ = tn.expect([b"bee"], 1.0)
        assert match_object

        tn.write(b"56scoo78" + b"\r\n")
        _, match_object, _ = tn.expect([b"bee"], 1.0)
        assert match_object

        tn.close()
Пример #13
0
class MozRepl(object):
    def __init__(self, host="127.0.0.1", port=4242):
        self.host = host
        self.port = port
    
    def __enter__(self):
        #Start Telnet
        self.t = Telnet(self.host, self.port)
        #Wait for Prompt, and detect repl name at the same time
        _, match, _ = self.t.expect([br'(repl\d*)> '], timeout = 250)
        if match is None:
            raise Exception('Timeout: Could not detect prompt')
        self._context = match.group(1)
        self.context = match.group(1).decode()
        self.prompt = match.group(0)
        return self
    
    def __exit__(self, type, value, traceback):
        self.t.close()
        del self.t
        
    def js(self, command, **kwargs):
        #TODO: look for .....> which would mean repl expects a continuation line 
        #(Then send a ; to abort and hopefully get an error)
        from json import dumps
        args = sorted([(k, v) for k, v in kwargs.items()])
        arglist = ",".join(["repl"] + [x[0] for x in args])
        argvalues = ",".join([self.context] + [dumps(x[1]) for x in args])
        cmd = "(function({}){{ {} }})({});".format(arglist, command, argvalues) 
        self.t.write(cmd.encode() + b"\n")
        x = self.t.read_until(self.prompt).decode('utf-8', errors = 'replace')
        return x[:-(len(self.prompt))]
Пример #14
0
    class Session:
        def __init__(self, host, port, user, pswd):
            self.telnet = Telnet(host=host, port=port, timeout=5)
            self.read_until(match='Login id:', timeout=5)
            self.write(buffer=user + '\n')
            self.read_until(match='Password:'******'\n')
            self.read_until(match='Welcome %s. HELP for a list of commands' %
                            user,
                            timeout=5)

        def is_user_registered(self, user):
            self.write('verify %s\n' % user)
            res = self.telnet.expect([b'exists', b'does not exist'])
            return res[0] == 0

        def create_user(self, user, pswd):
            self.write('adduser %s %s\n' % (user, pswd))
            self.read_until(match='User %s added' % user, timeout=5)

        def reset_passwoerd(self, user, pswd):
            self.write('setpassword %s %s\n' % (user, pswd))
            self.read_until(match='Password for %s reset' % user, timeout=5)

        def quit(self):
            self.write('quit\n')

        # service
        def read_until(self, match, timeout=5):
            self.telnet.read_until(match.encode('ascii'), timeout=timeout)

        def write(self, buffer):
            self.telnet.write(buffer.encode('ascii'))
Пример #15
0
    class Session:
        def __init__(self, host, port, username, password):
            #тут логин и пароль - для подключения к почтовому серверу
            self.telnet = Telnet(host, port, 5)
            # соединение установили
            # 5 - таймаут в сек
            self.read_until("Login id:", 5)
            self.write(username + "\n")
            self.read_until("Password:"******"\n")
            self.read_until("Welcome root. HELP for a list of commands", 5)

        def read_until(self, text, timeout):
            self.telnet.read_until(text.encode('ascii'), timeout)

        def write(self, text):
            self.telnet.write(text.encode('ascii'))

        def is_users_registered(self, username):
            self.write("verify %s\n" % username)
            res = self.telnet.expect([b"exists", b"does not exist"])
            return res[0] == 0

        def create_user(self, username, password):
            self.write("adduser %s %s\n" % (username, password))
            self.read_until("User %s added" % username, 5)

        def reset_password(self, username, password):
            self.write("setpassword %s %s\n" % (username, password))
            self.read_until("Password for %s reset" % username, 5)

        def quit(self):
            self.write("quit")
Пример #16
0
def telnetMain():
    print "DEBUG: Opening telnet handle"
    tn = Telnet("localhost", 6667)
    tn.set_debuglevel(5)
    tn.read_until("BitlBee-IRCd initialized, please go on")

    tn.write("NICK " + nickname +"\n")
    tn.write("USER " + username + " 8 *: " + realname + "\n")
    tn.read_until("identify yourself", 3)

    print "DEBUG: Joining bitlbee"
    tn.write("JOIN &bitlbee\n")
    tn.write("PRIVMSG &bitlbee :identify " + regpass + "\n")
    tn.read_until("facebook - Logging in: Logged in", 3)

    print "DEBUG: Joining channel"
    tn.write("JOIN " + fbchan + "\n")

    print "DEBUG: Telnetmain finished"
    regexes = nerdreply.regexes()
    while True:
        (idx, match, output) = tn.expect(regexes)
        print "DEBUG: idx=" + str(idx)
        print "DEBUG: match=" + match.group(0)
        cleaned = cleanup(match.group(0))
        print "DEBUG: cleanedUp=" + cleaned

        sendMsg(tn, nerdreply.processRequest(idx, cleaned))
Пример #17
0
    class Session:
        def __init__(self, host, port, username, password):
            self.telnet = Telnet(host, port, 5)
            self.read_until("Login id:")
            self.write(username + "\n")
            self.read_until("Password:"******"\n")
            self.read_until("Welcome root. HELP for a list of commands")

        def read_until(self, text):
            self.telnet.read_until(text.encode("ascii"), 5)

        def write(self, text):
            self.telnet.write(text.encode("ascii"))

        def is_users_registered(self, username):
            self.write("verify %s\n" % username)
            res = self.telnet.expect([b"exists", b"does not exist"])
            return res[0] == 0

        def create_user(self, username, password):
            self.write("adduser %s %s\n" % (username, password))
            self.read_until("User %s added" % username)

        def reset_password(self, username, password):
            self.write("setpassword %s %s\n" % (username, password))
            self.read_until("Password for %s reset" % username)

        def quit(self):
            self.write("quit\n")
Пример #18
0
    class Session:
        # данные для доступа к почтовому серверу
        def __init__(self, host, port, username, password):
            # установка соединения
            self.telnet = Telnet(host, port, 5)
            # указание данных для входа
            self.read_until("Login id:")
            self.write(username + "\n")
            self.read_until("Password:"******"\n")
            self.read_until("Welcome root. HELP for a list of comamnds")

        def read_until(self, text):
            #вспомогательный метод для перекодировки строк в байтовые, переписали базовую функцию telnet.read_until
            self.telnet.read_until(text.encode('ascii'), 5)

        def write(self, text):
            #вспомогательный метод для перекодировки строк в байтовые, переписали базовую функцию telnet.write
            self.telnet.write(text.encode('ascii'))

        def is_users_registered(self, username):
            self.write("verify %s\n" % username)
            res = self.telnet.expect([b"exists", b"does not exist"])
            return res[0] == 0

        def create_user(self, username, password):
            self.write("adduser %s %s\n" % (username, password))
            self.read_until("User %s added" % username)

        def reset_password(self, username, password):
            self.write("setpassword %s %s\n" % (username, password))
            self.read_until("Password for %s reset" % username)

        def quit(self):
            self.write("quit\n")
Пример #19
0
    class Session:
        def __init__(
            self, host, port, username, password
        ):  # these are login/password data of the mail server, and not the user's data
            self.telnet = Telnet(
                host, port,
                5)  # 5 seconds timeout waiting the server to connect
            self.read_until("Login id:")
            self.write(username + "\n")
            self.read_until("Password:"******"\n")
            self.read_until("Welcome root.HELP for a list of commands:")

        def read_until(self, text):
            self.telnet.read_until(text.encode('ascii'), 5)

        def write(self, text):
            self.telnet.write(text.encode('ascii'))

        def is_users_registered(self, username):
            self.write("verify %s\n" % username)
            # "b" stands for byte strings used in telnet
            res = self.telnet.expect([b"exists", b"does not exist"])
            return res[0] == 0  #the user exists

        def create_user(self, username, password):
            self.write("adduser %s %s\n" % (username, password))
            self.read_until("User %s added" % username)

        def reset_password(self, username, password):
            self.write("setpassword %s %s\n" % (username, password))
            self.read_until("Password for %s reset" % username)

        def quit(self):
            self.write("quit\n")
Пример #20
0
def tlnt_connect(doc, timeout):
    print2('connecting')
    tn = Telnet(doc['server'])
    print2('sending username')
    s = tn.read_until(b'Username: '******'login'] + '\n\r'
    tn.write(cmd.encode('ascii'))
    print2('sending password')
    s = tn.read_until(b'Password: '******'password'] + '\n\r'
    tn.write(cmd.encode('ascii'))
    t = tn.expect([b'\r\n/', b'\r\nUser authorization failure\r\n'])
    if t[0] in [1, -1]:
        tn.close()
        return
    s = t[2]
    s = s.decode('ascii')
    i1 = s.find('AT')
    i2 = s.find('/')
    dd = s[i1+3:i2]
    hh = s[i2+1:i2+3]
    doc['dd2'] = dd
    doc['hh2'] = hh
    hhh = 24*int(dd) + int(hh)
    hhh -= int(doc['hh'])
    if hhh < 0:
        hhh = 0
    doc['dd1'] = '%d' % (hhh/24)
    doc['hh1'] = '%d' % (hhh%24)
    return tn
Пример #21
0
    class Session:

        def __init__(self, host, port, username, password): # доступ к почтовому серверу
            self.telnet = Telnet(host, port, 5)
            self.read_until("Login id:")
            self.write(username + '\n') # it's very important to have \ slash, not /
            self.read_until("Password:"******"Welcome root. HELP for a list of commands")

        def is_users_registered(self, username):
            self.write("verify %s \n" % username)
            res = self.telnet.expect([b"exists", b"does not exist"])
            return res[0] == 0

        def create_user(self, username, password):
            self.write("adduser %s %s\n" % (username, password))
            self.read_until("User %s added" % username)

        def reset_password(self, username, password):
            self.write("setpassword %s %s\n" % (username, password))
            self.read_until("Password for %s reset" % username)

        def quit(self):
            self.write("quit\n")

        def read_until(self, text): # to convert our string into byte
            self.telnet.read_until(text.encode("ascii"), 5)

        def write(self, text): # to convert our string into byte
            self.telnet.write(text.encode("ascii"))
Пример #22
0
def run_telnet_session(session_yaml_file, outstream):
    from telnetlib import Telnet
    import yaml

    with open(session_yaml_file) as infile:
        session_config = yaml.load(infile)

    tn = Telnet(host=session_config["host"], port=session_config["port"])

    #tn.set_debuglevel(7)

    output = {}
    expected_prompts = [bytes(prompt, "utf8") \
              for prompt in session_config["session"].keys()]

    commands = session_config["session"]

    while True:
        index, match, text = tn.expect(expected_prompts)
        cmd = commands[str(expected_prompts[index], "utf8")]
        if isinstance(cmd, str):
            tn.write(bytes(cmd + "\r", "utf8"))
            output[expected_prompts[index]] = text

        elif isinstance(cmd, list):
            output[expected_prompts[index]] = {}
            for c in cmd:
                tn.write(bytes(c + "\r", "utf8"))
                result = tn.read_until(expected_prompts[index])
                output[expected_prompts[index]][c] = result
                if c == "exit":
                    break

        print(output, file=outstream)
Пример #23
0
    class Session:
        def __init__(self, host, port, username, password, timeout=5):
            self.telnet = Telnet(host, port, timeout)
            self.read_until("Login id:")
            self.write(username)
            self.read_until("Password:"******"Welcome %s. HELP for a list of commands" %
                            username)

        def read_until(self, text, timeout=5):
            self.telnet.read_until(text.encode("ascii"), timeout)

        def write(self, text):
            self.telnet.write((text + "\n").encode("ascii"))

        def is_user_exist(self, username):
            self.write("verify %s" % username)
            result = self.telnet.expect([b"exists", b"does not exist"])
            return result[0] == 0

        def create_user(self, username, password, timeout=5):
            self.write("adduser %s %s" % (username, password))
            self.read_until("User %s added" % username)

        def reset_password(self, username, password, timeout=5):
            self.write("setpassword %s %s" % (username, password))
            self.read_until("Password for %s reset" % username)

        def quit(self):
            self.write("quit")
Пример #24
0
class TelnetCon:
    def __init__(self, host, pw, db):
        self.tn = Telnet(host, 23)
        self.tn.set_debuglevel(db)
        #password = b'Elena9596'

        print(self.tn.read_until(b":"))
        self.tn.write(str.encode(pw))
        self.tn.write(b'\r')

        n, match, previous_text = self.tn.expect([br'Invalid', br'success'])
        if n == 0:
            print(previous_text)
        else:
            print(previous_text)

    def setTemp(self, temp):
        self.send(f'M104 S{temp}')

    def waitForMovesToFinish(self):
        self.send('M400')

    def dwell(self, seconds):
        self.send(f'G4 S{seconds}')

    def waitForHeater(self):
        self.send('M116')

    def send(self, msg):
        self.tn.write(str.encode(msg))
        self.tn.write(b'\r')

    def close(self):
        self.tn.close()
Пример #25
0
    class Session():
        def __init__(self, host, port, username, password):
            self.telnet = Telnet(host, port, 5)
            self.read_until("Login id:")
            self.write(username + "\n")
            self.read_until("Password:"******"\n")
            self.read_until('Welcome root. HELP for a list of commands')

        def read_until(self, text):
            self.telnet.read_until(text.encode('ascii'), 5)

        def write(self, text):
            self.telnet.write(text.encode('ascii'))

        def is_users_registred(self, username):
            self.write("verify %s \n" % username)
            res = self.telnet.expect([b"does not exist", b"exist"])
            return res[0] == 1

        def create_user(self, username, password):
            self.write(f"adduser {username} {password} \n")
            self.read_until(f"User {username} added")

        def reset_password(self, username, password):
            self.write(f"setpassword {username} {password} \n")
            self.read_until(f"Password for {username} reset")

        def quit(self):
            self.write("quit\n")
Пример #26
0
    class Session:
        def __init__(self, host, port, username, password):
            self.telnet = Telnet(host, port, timeout=10)
            self.read_until("Login id:")
            self.write(username + "\n")
            self.read_until("Password:"******"\n")
            self.read_until(
                "Welcome {}. HELP for a list of commands".format(username))

        def read_until(self, text):
            self.telnet.read_until(text.encode('ascii'), 10)

        def write(self, text):
            self.telnet.write(text.encode("ascii"))

        def is_user_registred(self, username):
            self.write("verify {}\n".format(username))
            res = self.telnet.expect([b"exists", b"does not exist"])
            return res[0] == 0

        def create_user(self, username, password):
            self.write("adduser {} {}\n".format(username, password))
            self.read_until("User {} added".format(username))

        def reset_password(self, username, password):
            self.write("setpassword {} {}\n".format(username, password))
            self.read_until("Pasword for {} reset".format(username))

        def quite(self):
            self.write("quite\n")
Пример #27
0
 def _getresp(self):
     if not self.inited:
         return
     (i, match, resp) = Telnet.expect(self, self.prompt, self.timeout)
     # Remove the terminating prompt.
     # Everything preceding it is the response.
     return split(resp, '\n')[:-1]
Пример #28
0
    def _run_command(self, cmd: str, ok="OK") -> bool:
        """
        sends a telnet command to the host
        :param cmd:
        :return: bool successful
        """

        telnet = Telnet(self.ip, self.telnet_port, 60)
        try:
            response = telnet.read_until(b'>', timeout=0.1)
            self.logger.debug("Intial response is: {0!s}".format(response.decode()))

            # we MUST wait a little bit before writing to ensure that the stream isnt being written to.
            time.sleep(0.5)
            # encode to ascii and add LF. unfortunately this is not to the telnet spec (it specifies CR LF or LF CR I'm ns)
            telnet.write(cmd.encode("ascii") + b"\n")
            ok_regex = re.compile(b'.*'+ok.encode("ascii")+b'.*')
            response = telnet.expect([ok_regex], timeout=30)
            if response[0] < 0:
                return False
            else:
                return True
        except:
            self.logger.error(traceback.format_exc())
            return False
        finally:
            telnet.close()
Пример #29
0
    class Session:
        def __init__(self, host, port, username, password):
            self.telnet = Telnet(host, port, 5)
            self.read_until("Login id:")
            self.write(username +"\n")
            self.read_until("Password:"******"\n")
            self.read_until("Welcome root.HELP for a list of commands")

        def read_until(self, text):
            self.telnet.read_until(text.encode('ascii'), 5)

        def write(self, text):
            self.telnet.write(text.encode('ascii'))

        def is_user_registered(self, username):
            self.write("verify %s\n" % username)
            res = self.telnet.expect([b"exists", b"does not exist"])
            return res[0] == 0

        def create_user(self, username, password):
            self.write("adduser %s %s\n" % (username, password))
            self.read_until("User %s added" % username)

        def reset_password(self, username, password):
            self.write("setpassword %s %s\n" % (username, password))
            self.read_until("Password for %s reset" % username)

        def quit(self):
            self.write("quit\n")
Пример #30
0
    class Session:
        def __init__(self, host, port, username, password):
            self.telnet = Telnet(host, port, 5)
            self.read_until('Login id:')
            self.write(username + '\n')
            self.read_until('Password:'******'\n')
            self.read_until('Welcome root. HELP for a list of commands')

        def read_until(self, text):
            self.telnet.read_until(text.encode('ascii'), 5)

        def write(self, text):
            self.telnet.write(text.encode('ascii'))

        def is_user_registered(self, username):
            self.write('verify {}'.format(username) + '\n')
            res = self.telnet.expect([b'exists', b'does not exist'])
            return res[0] == 0

        def create_user(self, username, password):
            self.write('add user {} {}'.format(username, password) + '\n')
            self.read_until('User %s added:' % username)

        def reset_password(self, username, password):
            self.write('setpassword {} {}'.format(username, password) + '\n')
            self.read_until('Password for {} added:'.format(username))

        def quit(self):
            self.telnet.write('quit' + '\n')
Пример #31
0
    class Session:
        def __init__(self, host, port, username, password):
            self.timeout = 5
            self.telnet = Telnet(host, port, self.timeout)
            self.read_until("Login id")
            self.write(username + '\n')
            self.read_until("Password")
            self.write(password + '\n')
            self.read_until("Welcome %s. HELP for a list of commands" %
                            username)

        def read_until(self, text):
            self.telnet.read_until(text.encode('ascii'), self.timeout)

        def write(self, text):
            self.telnet.write(text.encode('ascii'))

        def create_user(self, user, pwd):
            self.write("adduser %s %s \n" % (user, pwd))
            self.read_until("User %s added" % user)

        def is_user_exsists(self, user):
            self.write("verify %s \n" % user)
            res = self.telnet.expect([b"exists", b"does not exist"],
                                     self.timeout)
            return res[0] == 0

        def set_password_user(self, user, pwd):
            self.write("setpassword %s %s \n" % (user, pwd))
            self.read_until("Password for %s reset" % user)

        def quit(self):
            self.write("quit")
Пример #32
0
    class Session:
        def __init__(self, host, port, username, password):
            # Создание соединение с таймаутом 5 сек
            self.telnet = Telnet(host, port, 5)
            # Читаем до тех пор, пока не появляется строчка
            self.read_until("Login id:")
            # Вводим логин
            self.write(username + "\n")
            self.read_until("Password:"******"\n")
            self.read_until("Welcome root. HELP for a list of commands")

        def read_until(self, text):
            self.telnet.read_until(text.encode('ascii'), 5)

        def write(self, text):
            self.telnet.write(text.encode('ascii'))

        def is_user_registered(self, username):
            self.write("verify %s\n" % username)
            res = self.telnet.expect([b"exists", b"does not exist"])
            # Если 0, значит пользователь существует
            return res[0] == 0

        def create_user(self, username, password):
            self.write("adduser %s %s\n" % (username, password))
            self.read_until("User %s added" % username)

        def reset_password(self, username, password):
            self.write("setpassword %s %s\n" % (username, password))
            self.read_until("Password for %s reset" % username)

        def quit(self):
            self.write("quit\n")
Пример #33
0
    class Session:
        def __init__(
            self, host, port, username, password
        ):  # не те логин и пароль что передаются в метод ensur_user_exist , это для длступа к почтовому серверу
            self.telnet = Telnet(host, port, 5)  #timeout 5
            self.read_until("Login id:")
            self.write(username + "\n")
            self.read_until("Password:"******"\n")
            self.read_until("Welcome root. HELP for a list of commands")

        def read_until(self, text):
            self.telnet.read_until(text.encode('ascii'), 5)

        def write(self, text):
            self.telnet.write(text.encode('ascii'))

        def is_user_registered(self, username):
            self.write("verify %s\n" % username)
            res = self.telnet.expect([b"exists", b"does not exist"])
            return res[0] == 0

        def create_user(self, username, password):
            self.write("adduser %s %s\n" % (username, password))
            self.read_until("User %s added" % username)

        def reset_password(self, username, password):
            self.write("setpassword %s %s\n" % (username, password))
            self.read_until("Password for %s reset" % username)

        def quit(self):
            self.write("quit\n")
Пример #34
0
    class Session:

        def __init__(self, host, port, username, password):
            self.telnet = Telnet(host, port, 5)
            self.read_until('Login id:')
            self.write(username + '\n')
            self.read_until('Password:'******'\n')
            self.read_until('Welcome %s. HELP for a list of commands' % username)

        def read_until(self, text):
            self.telnet.read_until(text.encode('ascii'), 5)

        def write(self, text):
            self.telnet.write(text.encode('ascii'))

        def is_user_registered(self, username):
            self.write('verify %s\n' % username)
            result = self.telnet.expect([b'exists', b'does not exist'])
            return result[0] == 0

        def create_user(self, username, password):
            self.write('adduser %s %s\n' % (username, password))
            self.read_until('User %s added' % username)

        def reset_password(self, username, password):
            self.write('setpassword %s %s\n' % (username, password))
            self.read_until('Password for %s reset' % username)

        def quit(self):
            self.write('quit\n')
Пример #35
0
def get_cluster_info(host, port, ignore_cluster_errors=False):
    """
    return dict with info about nodes in cluster and current version
    {
        'nodes': [
            'IP:port',
            'IP:port',
        ],
        'version': '1.4.4'
    }
    """
    client = Telnet(host, int(port))
    client.write(b'version\n')
    res = client.read_until(b'\r\n').strip()
    version_list = res.split(b' ')
    if len(version_list) not in [2, 3] or version_list[0] != b'VERSION':
        raise WrongProtocolData('version', res)
    version = version_list[1]
    if StrictVersion(smart_text(version)) >= StrictVersion('1.4.14'):
        cmd = b'config get cluster\n'
    else:
        cmd = b'get AmazonElastiCache:cluster\n'
    client.write(cmd)
    regex_index, match_object, res = client.expect(
        [re.compile(b'\n\r\nEND\r\n'),
         re.compile(b'ERROR\r\n')])
    client.close()

    if res == b'ERROR\r\n' and ignore_cluster_errors:
        return {
            'version': version,
            'nodes': ['{0}:{1}'.format(smart_text(host), smart_text(port))]
        }

    ls = list(filter(None, re.compile(br'\r?\n').split(res)))
    if len(ls) != 4:
        raise WrongProtocolData(cmd, res)

    try:
        version = int(ls[1])
    except ValueError:
        raise WrongProtocolData(cmd, res)
    nodes = []
    try:
        for node in ls[2].split(b' '):
            host, ip, port = node.split(b'|')
            try:
                # Attempt to connect to node
                node_conn = Telnet(ip or host, port, timeout=3)
            except:
                # Couldn't connect to node intime, do not add to list
                continue
            else:
                node_conn.close()
                nodes.append('{0}:{1}'.format(smart_text(ip or host),
                                              smart_text(port)))
    except ValueError:
        raise WrongProtocolData(cmd, res)
    return {'version': version, 'nodes': nodes}
Пример #36
0
def test_telnet_service_mock_add_banner():
    with TelnetServiceMock("127.0.0.1", 8023,
                           scenario=TelnetScenario.GENERIC) as target:
        banner = b"Scoobeedoobeedoo where are you?"
        target.add_banner(banner)

        assert target.host == "127.0.0.1"
        assert target.port == 8023

        tn = Telnet(target.host, target.port, timeout=1.0)

        _, match_object, _ = tn.expect([banner], 1.0)
        assert match_object

        _, match_object, foo = tn.expect([b"Login: "******"login: "], 1.0)
        assert match_object, foo.decode()
        tn.close()
Пример #37
0
def get_cluster_info(host, port, ignore_cluster_errors=False):
    """
    return dict with info about nodes in cluster and current version
    {
        'nodes': [
            'IP:port',
            'IP:port',
        ],
        'version': '1.4.4'
    }
    """
    client = Telnet(host, int(port))
    client.write(b'version\n')
    res = client.read_until(b'\r\n').strip()
    version_list = res.split(b' ')
    if len(version_list) not in [2, 3] or version_list[0] != b'VERSION':
        raise WrongProtocolData('version', res)
    version = version_list[1]
    if StrictVersion(smart_text(version)) >= StrictVersion('1.4.14'):
        cmd = b'config get cluster\n'
    else:
        cmd = b'get AmazonElastiCache:cluster\n'
    client.write(cmd)
    regex_index, match_object, res = client.expect([
        re.compile(b'\n\r\nEND\r\n'),
        re.compile(b'ERROR\r\n')
    ])
    client.close()

    if res == b'ERROR\r\n' and ignore_cluster_errors:
        return {
            'version': version,
            'nodes': [
                '{0}:{1}'.format(smart_text(host),
                               smart_text(port))
            ]
        }

    ls = list(filter(None, re.compile(br'\r?\n').split(res)))
    if len(ls) != 4:
        raise WrongProtocolData(cmd, res)

    try:
        version = int(ls[1])
    except ValueError:
        raise WrongProtocolData(cmd, res)
    nodes = []
    try:
        for node in ls[2].split(b' '):
            host, ip, port = node.split(b'|')
            nodes.append('{0}:{1}'.format(smart_text(ip or host),
                                        smart_text(port)))
    except ValueError:
        raise WrongProtocolData(cmd, res)
    return {
        'version': version,
        'nodes': nodes
    }
Пример #38
0
def QYT_TelnetClient(ip, username, password, enable, *cmds):
	tn = Telnet(ip, 23)
	rackreply = tn.expect([],timeout=1)[2].decode().strip()#读取回显
	print(rackreply)#打印回显
	tn.write(username.encode())#任何字串都需要转成二进制字串
	tn.write(b'\n')#注意一定要打回车
	time.sleep(1)#在命令之间留出一定的时间间隔!否则路由器可能反应不过来
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	print(rackreply)
	tn.write(password.encode())	
	tn.write(b'\n')
	time.sleep(1)
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	print(rackreply)
	tn.write(b'enable\n')
	time.sleep(1)
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	print(rackreply)
	tn.write(enable.encode())
	tn.write(b'\n')
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	print(rackreply)
	time.sleep(1)
	for cmd in cmds:#读取命令,并且逐个执行!
		tn.write(cmd.encode() + b'\n')
		rackreply = tn.expect([],timeout=1)[2].decode().strip()
		print(rackreply)
		time.sleep(1)
	tn.write(b'exit\n')
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	print(rackreply)
	tn.close()
Пример #39
0
 def login(self):
     user = '******'.format(self.user)
     pwd = '{0}\n'.format(self.password)
     tn = Telnet(self.ip, 23, 5)
     res = tn.expect(['Username:'******'Password:'******'>'], 5)
     if res[0] == -1:
         tn.close()
         return False
     tn.write('system-view\n')
     tn.read_until(']')
     return tn
Пример #40
0
def QYT_TelnetClient(ip, username, password, cmd):
	tn = Telnet(ip, 23)
	rackreply = tn.expect([],timeout=1)[2].decode().strip()#读取回显
	#print(rackreply)#打印回显
	tn.write(username.encode())#任何字串都需要转成二进制字串
	tn.write(b'\n')#注意一定要打回车
	time.sleep(1)#在命令之间留出一定的时间间隔!否则路由器可能反应不过来
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	#print(rackreply)
	tn.write(password.encode())	
	tn.write(b'\n')
	time.sleep(1)
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	#print(rackreply)

	tn.write('terminal length 0'.encode() + b'\n')
	time.sleep(1)
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	#print(rackreply)

	tn.write(cmd.encode() + b'\n')
	time.sleep(1)
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	#print(rackreply)
	result = rackreply
	time.sleep(1)
	tn.write(b'exit\n')
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	#print(rackreply)
	tn.close()
	return result
Пример #41
0
def main(hostname, username, password):
    t = Telnet(hostname)
    # t.set_debuglevel(1)        # uncomment to get debug messages
    t.set_option_negotiation_callback(process_option)
    t.read_until(b'login:'******'utf-8') + b'\r')
    t.read_until(b'assword:', 10)    # first letter might be 'p' or 'P'
    t.write(password.encode('utf-8') + b'\r')
    n, match, previous_text = t.expect([br'Login incorrect', br'\$'], 10)
    if n == 0:
        print("Username and password failed - giving up")
    else:
        t.write(b'exec echo My terminal type is $TERM\n')
        print(t.read_all().decode('ascii'))
def main():
    tn = None
    outcome = None
    try:
        # Ensure there are no paralell runs of this script
        lock.acquire(timeout=5)

        # Connect and authenticate
        tn = Telnet(jcli['host'], jcli['port'])
        tn.set_option_negotiation_callback(process_option)
        
        # for telnet session debug:
        #tn.set_debuglevel(1000)
        
        tn.read_until('Authentication required', 16)
        tn.write("\r\n")
        tn.read_until("Username:"******"\r\n")
        tn.read_until("Password:"******"\r\n")

        # We must be connected
        idx, obj, response = tn.expect([r'Welcome to Jasmin (\d+\.\d+[a-z]+\d+) console'], 16)
        if idx == -1:
            raise jCliSessionError('Authentication failure')
        
        # Wait for prompt
        wait_for_prompt(tn)

        # Build outcome for requested key
        if args.d == 'smppcs':
            response = wait_for_prompt(tn, command = "stats --smppcs\r\n")
            smppcs = get_list_ids(response)
            outcome = {'data': []}
            for cid in smppcs:
                outcome['data'].append({'{#CID}': cid})
        elif args.d == 'users':
            response = wait_for_prompt(tn, command = "stats --users\r\n")
            users = get_list_ids(response)
            outcome = {'data': []}
            for uid in users:
                outcome['data'].append({'{#UID}': uid})
    except LockTimeout:
        print 'Lock not acquired, exiting'
    except AlreadyLocked:
        print 'Already locked, exiting'
    except Exception, e:
        print type(e)
        print 'Error: %s' % e
Пример #43
0
def main():
    tn = None
    outcome = None
    try:
        # Ensure there are no paralell runs of this script
        lock.acquire(timeout=5)

        # Connect and authenticate
        tn = Telnet(jcli["host"], jcli["port"])
        tn.set_option_negotiation_callback(process_option)

        # for telnet session debug:
        # tn.set_debuglevel(1000)

        tn.read_until("Authentication required", 16)
        tn.write("\r\n")
        tn.read_until("Username:"******"username"] + "\r\n")
        tn.read_until("Password:"******"password"] + "\r\n")

        # We must be connected
        idx, obj, response = tn.expect([r"Welcome to Jasmin ([0-9a-z\.]+) console"], 16)
        if idx == -1:
            raise jCliSessionError("Authentication failure")

        # Wait for prompt
        wait_for_prompt(tn)

        # Build outcome for requested key
        if args.d == "smppcs":
            response = wait_for_prompt(tn, command="stats --smppcs\r\n")
            smppcs = get_list_ids(response)
            outcome = {"data": []}
            for cid in smppcs:
                outcome["data"].append({"{#CID}": cid})
        elif args.d == "users":
            response = wait_for_prompt(tn, command="stats --users\r\n")
            users = get_list_ids(response)
            outcome = {"data": []}
            for uid in users:
                outcome["data"].append({"{#UID}": uid})
    except LockTimeout:
        print "Lock not acquired, exiting"
    except AlreadyLocked:
        print "Already locked, exiting"
    except Exception, e:
        print type(e)
        print "Error: %s" % e
class TelnetRemoteConn(object):

  def __init__(self,ip,port,timeout):
    self.ip_addr = ip
    self.port = port
    self.timeout = timeout
    self.telnet_session = None
    self.log = ""
    self.prompt = ""

  def open_session(self):
    try:
      self.telnet_session = Telnet(self.ip_addr,self.port,self.timeout)
      self.log += "Session to %s:%s opened" % (self.ip_addr,self.port)
    except socket.timeout:
      self.log += "Failed to open connection to %s" % self.ip_addr

  def login(self,username,password):
    prompts = [">","$","#"]
    if (self.telnet_session):
      self.log += self.telnet_session.read_until("sername",self.timeout)
      self.telnet_session.write(username + '\n')
      self.log += self.telnet_session.read_until("ssword",self.timeout)
      self.telnet_session.write(password + '\n')
      self.prompt = self.telnet_session.expect(prompts,self.timeout)[2]
      self.log += self.prompt
    else:
      self.log += "Unable to Login: No Connection"

  def logout(self):
    self.telnet_session.write("exit" + '\n')
    self.telnet_session.close()

  def send_command(self,command):
    if (self.telnet_session):
      self.telnet_session.write(command + '\n')
      time.sleep(1)
      output = self.telnet_session.read_very_eager()
      self.log += output
      output_list = output.split('\n')
      output_list = output_list[1:-1]
      output = '\n'.join(output_list)
      return output 
    else:
      self.log += "Unable to send command:  No connection"
Пример #45
0
def openTelnet(sIP):
    try:
        tn = Telnet(host=sIP,port=23)
        sleep(2)
        ind,re,strout=tn.expect(['login: '******'$ ','# '],2)
        print "ind:",ind, "strout:",strout
        print "user:"******"password:"******"login:"******"ascii"))
            tn.write(config.dongle.user+'\n')
            print "USER:%s" %(config.dongle.user)
            ret=tn.read_until("Password:"******"\n")
            print "P:%s" %(config.dongle.password)
            ret=tn.read_until(config.dongle.prompt,5)
    except Exception as e:
        print "Exception caught:", e
        tn = None    
    return tn
Пример #46
0
class rokuSB:
    def __init__(self, dtype):
        self.sb = Telnet()
        self.dpytype = dtype
        self.host = None

    def open(self, host):
        try:
            self.sb.open(host, 4444, 10)
            prompt = self.sb.expect([b'SoundBridge> ', b'sketch> '], 2)
            if (prompt[0] == -1):
                print("SB not responding")
                self.sb.close()
                return False

        except (ConnectionError, socket.error) as err:
            print("SoundBridge '{}', not found or connect failure = {}".format(host, err))
            return False

        # Save host for reopen()
        self.host = host
        # Set character encoding default
        self.msg(encoding='utf8')
        self.cmd("irman echo")
        return True

    def reopen(self):
        if (self.host is None):
            return False
        assert(self.sb.get_socket() is None)
        return self.open(self.host)

    def close(self):
        if (self.sb.get_socket() is None):
            return
        try:
            # self.cmd("sketch -c clear")
            self.cmd("sketch -c exit")
            self.cmd("irman off")
            self.cmd("exit")
        except socket.error:
            print("Socket error in close = {}", sys.exc_info())
        finally:
            if (self.sb.get_socket() is not None):
                self.sb.close()

    # Optional args to msg (soundbridge display)
    #
    # text          - default none - can be omitted to just set font and encoding
    # x,y  location - default 0,0
    # font          -
    # clear         - 0/1 force the display to clear first (default 0)
    # encoding      - set roku text encoding
    #
    def msg(self, **kwargs):
        x = kwargs.get('x', 0)
        y = kwargs.get('y', 0)
        text = kwargs.get('text')
        clear = kwargs.get('clear', False)
        font = kwargs.get('font')
        encoding = kwargs.get('encoding')

        if (encoding is not None):
            self.cmd("sketch -c encoding " + str(encoding))

        if (font is not None):
            self.cmd("sketch -c font " + str(font))

        if (text is None):
            return

        if (clear):
            self.clear()

        self.cmd('sketch -c text {} {} "{}"'.format(x, y, text))
        return

    def cmd(self, text):
        try:
            self.sb.write(text.encode('utf-8') + b'\n')
        except socket.error:
            print("Socket error in write = {}", sys.exc_info())
            if (self.sb.get_socket() is not None):
                self.sb.close()
            raise

    def clear(self):
        self.cmd("sketch -c clear")

    # Handle input and look for IR commands between panels
    def keyproc(self, timeout):
        self.cmd("irman intercept")
        try:
            msg = self.sb.expect([b'irman: (.*)$'], timeout)
        except EOFError:
            if (self.sb.get_socket() is not None):
                self.sb.close()
            raise

        # Got an IR code - pass it on to SB and exit app
        self.cmd("irman off")
        if (msg[0] == -1):
            return 'TIMEOUT'
        self.cmd("sketch -c exit")
        ir_cmd = msg[1].group(1)
        self.cmd("irman dispatch {}".format(ir_cmd))
        return ir_cmd
Пример #47
0
class Remote:
  def __enter__(self):
    self.t = Telnet(HOST)

    self.t.set_option_negotiation_callback(process_option)
    self.t.set_debuglevel(DEBUG_LEVEL)

    return self

  def __exit__(self, type, value, traceback):
    self.t.close()
    return False

  def is_on(self):
    self.t.write("?P\r\n")
    state = self.t.expect(["PWR1", "PWR0"], 0.2)
    return state[2] == "PWR0"

  def off(self):
    self.t.write("PF\r\n")

  # neet to set "network standby" to on in the receiver settings 
  # otherwise, this won't work
  def on(self):
    self.t.write("PO\r\n")
    time.sleep(0.2)
    self.t.write("PO\r\n")

  # defining the actions to take
  # between volume(-30) and volume(-40) is normally comfortable
  def volume(self, negDezibel):
    vol = negDezibel * 2 + 161
    self.t.write("%03dVL\r\n" % vol)

  def get_volume(self):
    try:
      self.t.write("?V\r\n")
      match = self.t.expect(["VOL\d\d\d"], 0.2)
      if match[0] == 0: # got valid volume
        return (int(match[2].strip()[3:]) - 161) / 2
    except:
      pass
    return -100


  def get_device(self):
    try:
      self.t.write("?F\r\n")
      match = self.t.expect(["FN\d\d"], 0.2)
      if match[0] == 0: # valid device
        return {
          'FN02': "tuner",
          "FN04": "PC",
          "FN10": "TV",
          "FN01": "AUX",
          "FN25": "Pi"
        }.get(match[2].strip(), "unknown")
    except:
      pass
    return "n/a"


  def select_tuner(self):
    self.t.write("02FN\r\n")

  def select_pc(self):
    self.t.write("04FN\r\n")

  def select_tv(self):
    self.t.write("10FN\r\n")

  def select_pi(self):
    self.t.write("25FN\r\n")

  def select_aux(self):
    self.t.write("01FN\r\n")

  def mute(self, should_mute):
    if should_mute:
      self.t.write("MO\r\n")
    else:
      self.t.write("MF\r\n")
Пример #48
0
class TelnetCheckConfig():
    """
    当該ホストへのtelnetを行い、指定した文字列を打って、戻り値を評価するライブラリ
    """
    expectuntil = ""
    debug = False
    promptName = ""
    def __init__(self, debug = False):
        self.debug = debug
        pass

    def dp(self, d):
        if self.debug == True:
            print(d)

    def connect(self, host, port, expectuntil, enablePass = "******"):
        """
        Ciscoノードへの接続
        :param host:
        :param port:
        :param expectuntil:
        :param enablePass:
        :return:
        """
        # 待ち受けよう文字列の準備
        self.promptName = expectuntil
        self.expectuntil = expectuntil.encode("ascii")
        prUsermode = self.expectuntil + ">".encode("ascii")
        prExecmode = self.expectuntil + "#".encode("ascii")
        prConfigmode = self.expectuntil + "\(".encode("ascii")

        #telnetする
        self.t = Telnet(host, port=port)
        # login直後のやさしさ(telnetからの応答を一つよみこむ
        (index, reobj, res) = self.t.expect([self.expectuntil], timeout = 1)
        if index == -1:
            return -1

        # 0x0aは最悪、show runとかで--more--してても抜けられる
        self.t.write(b"\r\n")
        # \r\nを送った場合、1回ダミーの設定のexpectを入れる
        (index, reobj, res) = self.t.expect([self.expectuntil])
        # 今のモードを識別する
        (index, reobj, res) = self.t.expect([prExecmode, prUsermode, prConfigmode], timeout=1)
        # enableの場合何もしない
        if index == 0:
            pass
        # loginならenableする。パスワードが必要ならログインする
        elif index == 1:
            self.t.write(b"enable\n")
            (index, reobj, res) = self.t.expect([prExecmode, b"Password"])
            if index == 1:
                self.write(enablePass)
        # configモードは抜ける
        elif index == 2:
            self.write("end")
        # 余計なログをひっかけないようにする
        self.write("ter len 0")
        self.write("conf t", rough=True)
        self.write("no logg con", rough=True)
        self.write("end")

    def write(self, cmd, rough= False):
        """
        :param cmd:
        :param rough: Trueならホスト名だけで次に行く.Falseならenableモードか確認する
        :return:
        """
        self.dp("send: {0}".format(cmd))
        self.t.write(cmd.encode("ascii") + b"\n")
        if not rough:
            waitWord = self.expectuntil + "#".encode("ascii")
        else:
            waitWord = self.expectuntil
        (index, reobj, res) = self.t.expect([waitWord])
        #self.dp("recv: {0}".format(res.decode("utf-8")))

    def do_singletest(self, cmd, p = [], n = []):
        """
        :param cmd: これを実施する
        :param p: 含まれるべき文字列
        :param n: 含まれてはならない文字列
        :return: 結果true or false
        """
        # 指定文字列の実行
        self.dp("send: {0}".format(cmd))
        self.t.write(cmd.encode("ascii") + b"\n")
        (index, reobj, res) = self.t.expect([self.expectuntil])

        # 応答を評価する
        res = res.decode("utf-8")
        stlt = SimpleTextLineTest(res, p, n, debug=True)
        is_pass = stlt.is_pass()
        # 結果の詳細を格納
        result = stlt.raw_result()
        stlt = None
        # 結果をターミナルに書く
        resultstr = self.result2str(result)
        for l in resultstr:
            self.write("!" + l)
        return is_pass

    def result2str(self, result):
        """
        ターミナルに出力するようの
        :param result:
        :return:
        """
        res = []
        for fp, type, pat, negline in result:
            l = ""
            l = l + "[OK]:" if fp else "[ERROR]:"
            if type == "p":
                l = l + "INCLUDE [{0}]".format(pat)
            elif type == "n":
                l = l + "NOT-INCLUDE [{0}]".format(pat)
            res.append(l)
        return res

    def disconnect(self):
        self.write("ter len 24")
        self.write("conf t", rough=True)
        self.write("logg con", rough=True)
        self.write("end")
        self.t.close()

    def test(self, diTests):
        res = []
        ipaddr = diTests.get("ipaddr", "127.0.0.1")
        port = diTests.get("port", "23")
        hostname = diTests.get("hostname", "localhost")
        prompt = diTests.get("prompt", hostname)
        self.connect(ipaddr, port, prompt)
        final_pass = True
        for t in diTests.get("tests", []):
            name = t.get("name", "NONAME")
            self.write("!!!!!!! BEGIN Test: {0}".format(name))
            cmd = t.get("cmd", [])
            p = t.get("include", [])
            n = t.get("notinclude", [])
            is_pass = self.do_singletest(cmd, p, n)
            final_pass = final_pass and is_pass
            self.write("!!!!!!! END")
            self.write("")
            res.append((name, is_pass))
        return (self.promptName, final_pass, res)

    def showRun(self, ipaddr, port, prompt, timeout = 5):
        r = self.connect(ipaddr, port, prompt)
        if r == -1:
            return (-1, None, "")
        self.t.write("show run |  exclude Last conf|Current c|Building".encode("ascii") + b"\n")
        (index, reobj, res) = self.t.expect([self.expectuntil + "#".encode("ascii")], timeout = 3)
        #pprint(res)
        # timeoutの時は、reobj = None, index = -1で返ります
        return(index, reobj, res.decode("utf-8"))

    def writeResult(self, result):
            """
            最終結果のコンソールへの表示
            :param result:
            :return:
            """
            self.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            self.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            finalResult = True
            for name, is_pass in result:
                s = "PASS" if is_pass else "FAIL"
                finalResult = finalResult and is_pass
                self.write("! [{0}]: {1}".format(s, name))
            self.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            self.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            self.write("! FINAL RESULT [{0}]".format("PASS" if finalResult else "FAIL"))

    def writeResult2stdout(self, result):
        """
        最終結果のターミナルへの表示
        :param result:
        :return:
        """
        print("")
        finalResult = True
        for name, is_pass in result:
            finalResult = finalResult and is_pass
        print("##### {0} [{1}]".format(self.promptName, "OK" if finalResult else "FAIL"))
        for name, is_pass in result:
            s = "PASS" if is_pass else "FAIL"
            finalResult = finalResult and is_pass
            print("  [{0}]: {1}".format(s, name))
Пример #49
0
class ZBController:
    def __init__(self):
        self.conn = Telnet()
        self.sequence = 0

    def open(self, hostname):
        Telnet.open(self.conn, hostname, 4900)

    def _network_command(self, command, args, status_prefix):
        self.write('network %s %s' % (command, args))
        _, match, _ = self.conn.expect(['%s (0x[0-9A-F]{2})' % status_prefix], timeout=2)
        if match is None:
            raise TimeoutError()
        return int(match.group(1), 0)

    def form_network(self, channel=19, power=0, pan_id = 0xfafa):
        status = self._network_command('form', '%d %d 0x%04x' %
                (channel, power, pan_id), 'form')
        if status == 0x70:
            #already in network
            pass
        elif status != 0x00:
            raise UnhandledStatusError()

    def leave_network(self):
        status = self._network_command('leave', '', 'leave')
        if status == 0x70:
            # already out of network
            pass
        elif status == 0x00:
            out = self.conn.read_until('EMBER_NETWORK_DOWN', timeout=2)
            if not out.endswith('EMBER_NETWORK_DOWN'):
                raise TimeoutError()
        else:
            raise UnhandledStatusError()

    def enable_permit_join(self):
        status = self._network_command('pjoin', '0xff', 'pJoin for 255 sec:')
        if status != 0x00:
            raise NetworkOperationError("Error enabling pjoin: 0x%x" % status)

    def disable_permit_join(self):
        status = self._network_command('pjoin', '0x00', 'pJoin for 0 sec:')
        if status == 0x00:
            print "Pjoin Disabled"
        else:
            print "Error disabling pjoin: 0x%x" % status

    def wait_for_join(self):
        _, match, _ = self.conn.expect(['Device Announce: (0x[0-9A-F]{4})'])
        if match is None:
            raise TimeoutError()
        print 'Device %s joined' % match.group(1)
        return int(match.group(1), 0)

    def send_zcl_command(self, destination, cmd, debug=False):
        payload = []
        for arg in cmd.args:
            payload += _list_from_arg(arg.type, arg.value)
        if debug:
            sys.stdout.write('raw 0x%04X {01 %02X %02X %s}' %
                    (cmd.cluster_code, self.sequence, cmd.code,
                    " ".join(["%02X" % x for x in payload])))
        else:
            self.write('raw 0x%04X {01 %02X %02X %s}' %
                    (cmd.cluster_code, self.sequence, cmd.code,
                    " ".join(["%02X" % x for x in payload])))
        self.write('send 0x%04X 1 1' % destination)
        self.sequence = self.sequence + 1 % 0x100
        #TODO: wait for response

    def send_zcl_ota_notify(self, destination, cmd):
        payload = []
        for arg in cmd.args:
            payload += _list_from_arg(arg.type, arg.value)
        self.write('zcl ota server notify 0x%04X %02X %s' %
                (destination, 1, " ".join(["0x%04X" % x for x in payload])))
        self.sequence = self.sequence + 1 % 0x100

    def bind_node(self, node_id, node_ieee_address, cluster_id, timeout = 10):
        '''
        Binds a destination node to us.
        Expects node_id and cluster_id as integers, and node_ieee_address as
        a string with hex bytes separated by spaces.
        '''
        self.write('zdo bind %d 1 1 %d {%s} {}' % (
                node_id, cluster_id, node_ieee_address))
        # note that we're basically waiting for any ZDO command, which is a little liberal
        # RX: ZDO, command 0x8021, status: 0x00
        _, match, _ = self.conn.expect(
                ["RX: ZDO, command 0x[0-9A-Za-z]{4}, status: 0x([0-9A-Za-z]{2})"], timeout=timeout)
        if match is None:
            raise AssertionError("TIMED OUT waiting for bind response")
        if match.group(1) != '00':
            raise AssertionError("Bind Request returned status %s" % match.group(1))


    def configure_reporting(self, destination, attribute, min_interval, max_interval, threshold):
        '''
        Configures the device to report the given attribute to the controller.
        '''
        if attribute.type in ['INT8U', 'INT16U', 'INT32U', 'INT8S', 'INT16S', 'INT32S']:
            threshold_value_list = _list_from_arg(attribute.type, threshold)
        else:
            threshold_value_list = [0]
        self.write('zcl global send-me-a-report %d %d %d %d %d {%s}' % (
            attribute.cluster_code, attribute.code, attribute.type_code,
            min_interval, max_interval, _hex_string_from_list(threshold_value_list)))
        self.write('send 0x%04X 1 1' % destination)

    def write_attribute(self, destination, attribute, value, timeout = 10):
        '''
        Writes an attribute on a device. Attributes are instances of
        ZCLAttribute.
        '''

        payload = _list_from_arg(attribute.type, value, strip_string_length=True)
        write_log(0, "Writing Attribute %s to %s" % (attribute.name,
                " ".join(['%02X' % x for x in payload])))
        self.write('zcl global write %d %d %d {%s}' %
                (attribute.cluster_code, attribute.code, attribute.type_code,
                " ".join(['%02X' % x for x in payload])))
        self.write('send 0x%04X 1 1' % destination)
        #RX len 4, ep 01, clus 0x0020 (Unknown clus. [0x0020]) FC 18 seq EC cmd 04 payload[00 ]
        _, match, _ = self.conn.expect(['RX len [0-9]+, ep [0-9A-Z]+, ' +
            'clus 0x%04X \([a-zA-Z0-9\.\[\]\(\) ]+\) .* cmd 04 payload\[([0-9A-Z ]*)\]' % attribute.cluster_code],
            timeout=timeout)
        #TODO: actually do something with the response

    def write_local_attribute(self, attribute, value):
        '''
        Writes an attribute that's local to the controller.
        '''
        payload = _list_from_arg(attribute.type, value)
        payload_string = " ".join(['%02X' % x for x in payload])
        self.write('write 1 %d %d 1 %d {%s}' % (
            attribute.cluster_code, attribute.code, attribute.type_code,
            payload_string))
        time.sleep(1)

    def make_server(self):
        self.write('zcl global direction 1')

    def make_client(self):
        self.write('zcl global direction 0')

#T000BD5C5:RX len 11, ep 01, clus 0x000A (Time) FC 18 seq 20 cmd 01 payload[00 00 00 E2 00 00 00 00 ]
#READ_ATTR_RESP: (Time)
#- attr:0000, status:00
#type:E2, val:00000000
    def read_attribute(self, destination, attribute, timeout=10):
        self.write('zcl global read %d %d' %
                (attribute.cluster_code, attribute.code))
        self.write('send 0x%04X 1 1' % destination)
        _, match, _ = self.conn.expect(['RX len [0-9]+, ep [0-9A-Z]+, ' +
            'clus 0x%04X \([a-zA-Z0-9\.\[\]\(\) ]+\) .* cmd 01 payload\[([0-9A-Z ]*)\]' % attribute.cluster_code],
            timeout=timeout)
        if match is None:
            raise AssertionError('TIMED OUT reading attribute %s' % attribute.name)
        payload = [int(x, 16) for x in match.group(1).split()]
        attribute_id = _pop_argument('INT16U', payload)
        status = _pop_argument('INT8U', payload)
        if status != 0:
            raise AssertionError('Attribute Read failed with status 0x%02X' % status)
        attribute_type_code = _pop_argument('INT8U', payload)
        attribute_type = zcl.get_type_string(attribute_type_code)
        return _pop_argument(attribute_type, payload)

    #T183FCD64:RX len 5, ep 01, clus 0x0020 (Unknown clus. [0x0020]) FC 18 seq D3 cmd 0B payload[03 00 ]
    def expect_zcl_command(self, command, timeout=10):
        '''
        Waits for an incomming message and validates it against the given
        cluster ID, command ID, and arguments. Any arguments given as None
        are ignored. Raises an AssertionError on mis-match or timeout.
        '''
        # read and discard any data already queued up in the buffer
        self.conn.read_eager()
        # we're pretty loose about what we accept as the incoming command. This is
        # mostly to more easily handle DefaultResponses, which are displayed
        # with their cluster ID as whatever cluster they're responding to
        _, match, _ = self.conn.expect(['RX .* cmd %02X payload\[([0-9A-Z ]*)\]'
            % command.code], timeout=timeout)
        if match is None:
            raise AssertionError("TIMED OUT waiting for " + command.name)
        payload = [int(x, 16) for x in match.group(1).split()]
        _validate_payload(command.args, payload)

    def write(self, msg):
        self.conn.write(msg + '\n')
Пример #50
0
class SqueezeServer():
    
    def __init__(self, address=None, port=None, player=None, dir=None, name=None):
        address = address or squeeze_kargs(dir=dir, name=name)[ADDRESS]
        port = port or squeeze_kargs(dir=dir, name=name)[PORT]
        player = player or squeeze_kargs(dir=dir, name=name)[PLAYER]
        LOG.debug('Connecting to {0}:{1}.'.format(address, port))
        self.__telnet = Telnet(address, port) 
        LOG.debug('Connected.')
        self.__pid = self.player_ids[player]
        LOG.debug('Found player {0} at {1}'.format(player, self.__pid))
    
    @property
    def player_ids(self):
        ids = {}
        for i in range(int(self.__global('player count ?'))):
            id = self.__global('player id {0} ?'.format(i))
            name = self.__global('player name {0} ?'.format(i))
            ids[name] = id
        return ids
    
    @property
    def playlist_tracks(self):
        return int(self.__player('playlist tracks ?'))
    
    @property
    def playlist_index(self):
        return int(self.__player('playlist index ?'))
    
    @property
    def playlist_remaining(self):
        return self.playlist_tracks - self.playlist_index 
    
    def __global(self, command):
        command = command.encode('utf8')
        if command.endswith(b'?'):
            response = command[:-1]
        else:
            response = b''
        response += b'([^\n]*)\n'
        LOG.debug('Sending {0}'.format(command))
        self.__telnet.write(command + b'\n')
        (_, match, _) = self.__telnet.expect([response])
        result = unquote(match.groups(1)[0].decode('utf8'), 'utf8')
        LOG.debug('Received: {0}'.format(result))
        return result
    
    def __player(self, command):
        return self.__global(quote(self.__pid) + ' ' + command)

    def playlist_add(self, url):
        LOG.info('Adding {0}.'.format(url))
        return unquote(self.__player('playlist add {0}'.format(quote(url))))
    
    @property
    def path(self):
        return unquote(self.__player('path ?'))
    
    @property
    def url(self):
        path = self.path
        if not path.startswith('file://'):
            path = 'file://' + path
        return path
Пример #51
0
 def _getresp(self):
     (i,match,resp) = Telnet.expect(self, self.prompt, self.timeout)
     # Remove the terminating prompt.
     # Everything preceding it is the response.
     return split(resp, '\n')[:-1]
# How your code might look if you intercept Telnet options yourself

from telnetlib import Telnet, IAC, DO, DONT, WILL, WONT, SB, SE, TTYPE

def process_option(tsocket, command, option):
    if command == DO and option == TTYPE:
        tsocket.sendall(IAC + WILL + TTYPE)
        print('Sending terminal type "mypython"')
        tsocket.sendall(IAC + SB + TTYPE + b'\0' + b'mypython' + IAC + SE)
    elif command in (DO, DONT):
        print('Will not', ord(option))
        tsocket.sendall(IAC + WONT + option)
    elif command in (WILL, WONT):
        print('Do not', ord(option))
        tsocket.sendall(IAC + DONT + option)

t = Telnet('localhost')
# t.set_debuglevel(1)        # uncomment this for debugging messages

t.set_option_negotiation_callback(process_option)
t.read_until(b'login:'******'brandon\n')
t.read_until(b'assword:', 5)  # so P can be capitalized or not
t.write(b'mypass\n')
n, match, previous_text = t.expect([br'Login incorrect', br'\$'], 10)
if n == 0:
    print("Username and password failed - giving up")
else:
    t.write(b'exec echo My terminal type is $TERM\n')
    print(t.read_all().decode('ascii'))
Пример #53
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
Пример #54
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)
Пример #55
0
class teamspeak:
  default_timeout_connect   = 5
  default_timeout_read      = 5
  
  def encode_string(self, string):
    """
    Encodes a string
    
    @param string: String to encode
    @type string: str
    
    @return: Encoded string
    """
    string = string.replace('\\', '\\\\')
    string = string.replace('/',  '\\/')
    string = string.replace(' ',  '\\s')
    string = string.replace('|',  '\\p')
    string = string.replace('\a', '\\a')
    string = string.replace('\b', '\\b')
    string = string.replace('\f', '\\f')
    string = string.replace('\n', '\\n')
    string = string.replace('\r', '\\r')
    string = string.replace('\t', '\\t')
    string = string.replace('\v', '\\v')
    
    return string

  def decode_string(self, string):
    """
    Decodes a string
    
    @param string: String to decode
    @type string: str
    
    @return: Secoded string
    """
    string = string.replace('\\\\', '\\')
    string = string.replace('\\/',  '/')
    string = string.replace('\\s',  ' ')
    string = string.replace('\\p',  '|')
    string = string.replace('\\a',  '\a')
    string = string.replace('\\b',  '\b')
    string = string.replace('\\f',  '\f')
    string = string.replace('\\n',  '\n')
    string = string.replace('\\r',  '\r')
    string = string.replace('\\t',  '\t')
    string = string.replace('\\v',  '\v')
    
    return string

  def __init__(self, server_host, server_port='10011'):
    """
    Class constructor
    """
    self.server_port  = server_port
    self.server_host  = server_host
  
  def connect(self, server_id=None):
    """
    Connects to the server
    
    @param server_id: Virtual Server's ID
    @type server_id: string 
    """
    data = ''
    
    try:
      self.net = Telnet(self.server_host, self.server_port, teamspeak.default_timeout_connect)
      data = self.net.read_until('\n', teamspeak.default_timeout_read)
      
      if data.rstrip() != 'TS3':
        print 'The server specified does not appear to be a TeamSpeak 3 server.'
        return False
      
    except:
      print 'Error connecting to server.'
      return False
    
    if (server_id):
      self.command('use %s' % (server_id))
    
    self.connected = True
    return True
  
  def read(self):
    """
    Reads from the server. This is useful for server notifications/events.
    
    @return: a list of data to parse
    @return: None if there is nothing to parse
    """
    data = self.net.read_very_eager()
      
    if len(data) > 1:
      data = data.split('\n')
      return data
    
    return None
      
  def disconnect(self):
    """
    Disconnects from the server.
    """
    self.net.write('quit\n')
    self.net.close()
    
  def login(self, client_login_name, client_login_password):
    """
    Logins to the server.
    
    @param client_login_name: Server query login
    @type client_login_name: str
    
    @param client_login_password: Server query password
    @type client_login_password: str
    """
    return self.command('login', { 'client_login_name' : client_login_name, 'client_login_password' : client_login_password})
    
  def parse_results(self, res):
    """
    Experimental parser.
    
    @param res: Raw data.
    @type res: str
    
    @return: dictionary of parsed items
    """
    out = {}
    
    res = res.replace('\r', '')
    for key in res.split(' '):
      value = key.split('=',1)
      
      if len(value) > 1:
        out[value[0]] = self.decode_string(''.join(value[1:]))
      else:
        out[key] = None
      
    return out
  
  def command(self, cmd, parameters={}, options=''):
    """
    Executes a command.
    
    @param cmd: Command to execute.
    @type cmd: str
    
    @param parameters: Parameters
    @type parameters: dict
    
    @param options: Options to pass.
    @type options: str
    
    @return: a list of dictionaries containing the results
    """
    ret = []
    
    out = cmd
    
    for key in parameters:
      out += ' %s=%s' % (key, self.encode_string(parameters[key]))
    
    out += ' ' + options + '\n'
    
    # print '->' + out
    self.net.write(out)
    
    data = self.net.expect(['(error id=)\d+ (msg=).*\n'], 5)
    
    results   = data[2].split('\n')
    error_id  = results[len(results)-2].split(' ')[1].split('=')[1]
    error_msg = results[len(results)-2].split(' ')[2].split('=')[1]
    
    if (error_id != '0'):
      print 'Server Error: %s, on command: %s' % (error_msg, cmd)
      return ret
      
    results = results[0]
    multi   = results.split('|')
    
    if len(multi) > 1:
      for item in multi:
        ret.append(self.parse_results(item))
    else:
      ret.append(self.parse_results(results))

    return ret
  
  def get_client_list(self, options=''):
    """
    Retrieves a list of clients with the given options.
    
    @param options: Options.
    @type options: str
    
    @return: Same as command
    """
    return self.command('clientlist', {}, options)
  
  def get_client_info(self, clid):
    """
    Retrieves information for a specific client.
    
    @param clid: Client's Id
    @type clid: str
    
    @return: Same as command
    """
    return self.command('clientinfo', {'clid' : clid})
Пример #56
0
def main():
    tn = None
    try:
        # Ensure there are no paralell runs of this script
        lock.acquire(timeout=5)

        # Connect and authenticate
        tn = Telnet(jcli['host'], jcli['port'])

        # for telnet session debug:
        #tn.set_debuglevel(1000)

        tn.set_option_negotiation_callback(process_option)

        
        tn.read_until('Authentication required', 16)
        tn.write("\r\n")
        tn.read_until("Username:"******"\r\n")
        tn.read_until("Password:"******"\r\n")

        # We must be connected
        idx, obj, response = tn.expect([r'Welcome to Jasmin (\d+\.\w+) console'], 16)
        if idx == -1:
            raise jCliSessionError('Authentication failure')
        version = obj.group(1)
        
        # Wait for prompt
        wait_for_prompt(tn)

        # Build outcome for requested key
        metrics = []
        for key in keys:
            if key == 'version':
                metrics.append(Metric(jcli['host'], 'jasmin[%s]' % key, version))
            elif type(key) == dict and 'smppsapi' in key:
                response = wait_for_prompt(tn, command = "stats --smppsapi\r\n")
                for k in key['smppsapi']:
                    metrics.append(Metric(jcli['host'], 'jasmin[smppsapi.%s]' % k, get_stats_value(response, k)))
            elif type(key) == dict and 'httpapi' in key:
                response = wait_for_prompt(tn, command = "stats --httpapi\r\n")
                for k in key['httpapi']:
                    metrics.append(Metric(jcli['host'], 'jasmin[httpapi.%s]' % k, get_stats_value(response, k)))
            elif type(key) == dict and 'smppcs' in key:
                # Get stats from statsm
                response = wait_for_prompt(tn, command = "stats --smppcs\r\n")
                smppcs = get_list_ids(response)
                
                # Get statuses from smppccm
                response = wait_for_prompt(tn, command = "smppccm -l\r\n")
                smppcs_status = get_smppcs_service_and_session(response)
                
                # Build outcome
                for cid in smppcs:
                    # From stats
                    response = wait_for_prompt(tn, command = "stats --smppc %s\r\n" % cid)
                    for k in key['smppcs']:
                        metrics.append(Metric(jcli['host'], 'jasmin[smppc.%s,%s]' % (k, cid), get_stats_value(response, k)))

                    # From smppccm
                    metrics.append(Metric(jcli['host'], 'jasmin[smppc.service,%s]' % (cid), smppcs_status[cid]['service']))
                    metrics.append(Metric(jcli['host'], 'jasmin[smppc.session,%s]' % (cid), smppcs_status[cid]['session']))
            elif type(key) == dict and 'users' in key:
                response = wait_for_prompt(tn, command = "stats --users\r\n")
                users = get_list_ids(response)
                for uid in users:
                    response = wait_for_prompt(tn, command = "stats --user %s\r\n" % uid)
                    for k in key['users']['httpapi']:
                        metrics.append(Metric(jcli['host'], 'jasmin[user.httpapi.%s,%s]' % (k, uid), get_stats_value(response, k, stat_type = 'HTTP Api')))
                    for k in key['users']['smppsapi']:
                        if k in ['bound_rx_count', 'bound_tx_count', 'bound_trx_count']:
                            r = get_stats_value(response, key = 'bound_connections_count', stat_type = 'SMPP Server')
                            r = json.loads(r.replace("'", '"'))
                            if k == 'bound_rx_count':
                                v = r['bind_receiver']
                            elif k == 'bound_tx_count':
                                v = r['bind_transmitter']
                            elif k == 'bound_trx_count':
                                v = r['bind_transceiver']
                        else:
                            v = get_stats_value(response, k, stat_type = 'SMPP Server')
                        metrics.append(Metric(jcli['host'], 'jasmin[user.smppsapi.%s,%s]' % (k, uid), v))

        #print metrics
        # Send packet to zabbix
        send_to_zabbix(metrics, zabbix_host, zabbix_port)
    except LockTimeout:
        print 'Lock not acquired, exiting'
    except AlreadyLocked:
        print 'Already locked, exiting'
    except Exception, e:
        print type(e)
        print 'Error: %s' % e
Пример #57
0
class Device(object):
	#Create Device object and assign type (EOS/EXOS), IP, port, and username/password.
	def __init__(self, type, address, port, login='******', passwd=''):
		self.username = login
		self.password = passwd
		print('Connecting to ' + type + ' device...')
		if type == 'EOS':
			self.reset_cmd = 'reset sys'
		elif type == 'EXOS':
			self.reset_cmd = 'reboot'
		else:
			raise ValueError("Invalid device type!")
		self.type = type
		self.tn = Telnet(address, port, 20)
		self.write('\n')
		self.read_until_prompt(10)
		print("Connected to %s:%d" % (address, port))
	
	#Reset the device.
	def reset(self):
		self.write([self.reset_cmd, 'y'])
			
	#Close telnet connection
	def closeconnection(self):
		self.tn.close()
		
	#Login to the device
	def login(self):
		self.write(self.username + '\n')
		self.write(self.password + '\n')
		if self.type == 'EXOS':
			temp = self.read_find('#', 4)
			if temp == None:
				print("Error logging into device: Incorrect username or bad password!\n")
				sys.exit()
			self.write('disable clipaging\n')
		else:
			temp = self.read_find('->', 4)
			if temp == None:
				print("Error logging into device: Incorrect username or bad password!\n")
				sys.exit()
			self.write('set cli completion disable\n')
		temp = temp + self.read()
		return temp
			
	#Write command(s) to the device.
	def write(self, commands, timeout=1):
		if isinstance(commands, str):
			#print('It is a string')
			self.tn.write(commands.encode('ascii') + b'\n')
			temp = self.read_until_prompt(timeout)
		else:
			#print('It is a list')
			temp = b''
			for command in commands:
				self.tn.write(command.encode('ascii') + b'\n')
				temp = temp + self.read_until_prompt(timeout)
		return temp
		
	#Read output
	def read(self):
		self.read_until_prompt(1)
		return self.tn.read_very_eager()

	#Read until given string.
	def read_until(self, s, timeout=300):
		return self.tn.read_until(s.encode('ascii'), timeout)
	
	#Same as read_until except returns null if timeout was reached (timeout was reached if the "read_until" string isn't in the return output).
	def read_find(self, s, timeout=300):
		temp = self.read_until(s, timeout)
		if s in str(temp):
			return temp
		else:
			return None
	
	#Read until OS prompt.
	def read_until_prompt(self, timeout=300):
		reYesNo = b'\([yY]/[nN](/q)*\)'
		(index, match, output) = self.tn.expect([reYesNo, b' # ', b'->', b'Username:'******'login:'******'[pP]assword'], timeout)
		#(index, match, output) = self.tn.expect([b' # ',b'->',reYesNo], timeout)
		return output

	#Clear running configuration on device.
	def clearConfig(self):
		if self.type == 'EOS':
			self.write(['clear config all', 'y'])
		if self.type == 'EXOS':
			self.write(['unconfig swi all', 'y'])
Пример #58
0
HOST = "192.168.217.166"
Level1Pass = "******"
PROMPT0 = "*"
PROMPT1 = "*>"
PROMPT2 = "**>"
PromptRE = re.compile(r'\*>?>?')
PromptRE_relay = re.compile(r'\=>?>?')
PassPromptRE = re.compile(r'Password: \?')

tn = Telnet(HOST)

if False:
    tn.write("QUI\r")
    print "Send: ", repr("QUI\r")
    n, m, l = tn.expect([PromptRE], 10.0)
    print "Read: ", repr(l.strip())

    tn.write("ACC\r")
    print "Send: ", repr("ACC\r")
    n, m, l = tn.expect([PassPromptRE], 10.0)
    print "Read: ", repr(l.strip())
    tn.write(Level1Pass + "\r")
    print "Send: ", repr(Level1Pass + "\r")

    n, m, l = tn.expect([PromptRE], 10.0)
    print "Read: ", repr(l.strip())


tn.write("POR 1\r")
print "Send: ", repr("POR 1\r")