当前位置: 首页>>代码示例>>Python>>正文


Python Telnet.read_very_eager方法代码示例

本文整理汇总了Python中telnetlib.Telnet.read_very_eager方法的典型用法代码示例。如果您正苦于以下问题:Python Telnet.read_very_eager方法的具体用法?Python Telnet.read_very_eager怎么用?Python Telnet.read_very_eager使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在telnetlib.Telnet的用法示例。


在下文中一共展示了Telnet.read_very_eager方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: set_state

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
    def set_state(self, state):
        s = 'On' if state else 'Off'

        tel = Telnet(self.bar.host)

        try:
            time.sleep(2.)

            garbage = tel.read_very_eager()
            print('GarbageRead:', garbage)

            w = "/%s %d" % (s, self.ident)
            msg = w.encode('ascii') + b"\r\n"
            print("Writing:", repr(msg))
            tel.write(msg)

            print("Reading:", repr(tel.read_until("NPS>", timeout=5)))

            time.sleep(1.)
            garbage = tel.read_very_eager()
            print('GarbageRead2:', garbage)

            self.state = state
        finally:
            tel.close()

        del tel

        time.sleep(0.5)
开发者ID:MerlijnWajer,项目名称:powerbars,代码行数:31,代码来源:wtibar.py

示例2: TelnetConnect

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
class TelnetConnect(object):
    def __init__(self,ip_addr,username,password):
        self.ip_addr=ip_addr
        self.username=username
        self.password=password
        try: 
            self.remote_conn= Telnet(self.ip_addr, TELNET_PORT, TELNET_TIMEOUT)
        except soket.timeout:
            sys.exit("Timeout Connection")

    def login(self,sleep_time=1):
        output=self.remote_conn.read_until('sername:',TELNET_TIMEOUT)
        self.remote_conn.write(self.username +'\n')
        output+=self.remote_conn.read_until('assword:', TELNET_TIMEOUT)
        self.remote_conn.write(self.password+'\n')
        time.sleep(sleep_time)
        output+=self.remote_conn.read_very_eager()
        return output

    def send_command(self,cmd,sleep_time=1):
        cmd=cmd.rstrip()
        self.remote_conn.write(cmd + '\n')
        time.sleep(sleep_time)
        return self.remote_conn.read_very_eager()
    
    def close_conn(self):
        self.remote_conn.close()
开发者ID:munirmurad2165,项目名称:python-adv-course,代码行数:29,代码来源:testw2p3.py

示例3: Bras

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
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:"], 5)
        # telnet ok, but no greetings from server
        if res[0] == -1:
            self.tn.close()
            return False
        self.tn.write(self.user + "\n")
        res = self.tn.expect(["Password:"], 5)
        if res[0] == -1:
            self.tn.close()
            return False
        self.tn.write(self.pwd + "\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
开发者ID:hh-h,项目名称:ossdev,代码行数:57,代码来源:Bras.py

示例4: tn_loop

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
def tn_loop(key_pipe):
    tn = Telnet(HOST, PORT)
    tn.write(b'\n')
    while True:
        if key_pipe.poll():
            tn.write(key_pipe.recv())
        data = tn.read_very_eager()
        print(data.decode(), end='')
开发者ID:Kopachris,项目名称:Kopachris,代码行数:10,代码来源:test_telnet.py

示例5: Login_to_device

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
 def Login_to_device(self):
    telnet_conn=Telnet(self.ip_addr,self.TELNET_PORT,self.TELNET_TIMEOUT)
    telnet_conn.read_until('sername:')
    telnet_conn.write(self.username + '\n')
    telnet_conn.read_until('assword:')
    telnet_conn.write(self.password + '\n')
    time.sleep(1)
    output=telnet_conn.read_very_eager()
    return  telnet_conn,output
开发者ID:karimjamali,项目名称:Course_Functions,代码行数:11,代码来源:course_functions.py

示例6: query

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
def query(server, port, player, commands):
    tn = Telnet(server, port)

    for command in commands:
        tn.write("%s %s ?\n" % (player, command))

    sleep(0.2)
    feedback = tn.read_very_eager().split('\n')
    results = [(cmd,unquote(res)[len(player)+len(cmd)+2:]) \
                 for cmd,res in zip(commands, feedback)]
    return dict(results)
开发者ID:kannaiah,项目名称:centurion,代码行数:13,代码来源:squeezebox.py

示例7: getIpInterfaces

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
def getIpInterfaces(host,user,password):
    timeout = 6
    port = 23
    remote_conn = Telnet(host,port,timeout)
    remote_conn.read_until(b"sername:")
    remote_conn.write(username.encode('ascii') + b"\n")
    remote_conn.read_until(b"assword:")
    remote_conn.write(password.encode('ascii') + b"\n")
    remote_conn.write(b"show ip int brief" + b"\n")
    time.sleep(2)
    output = remote_conn.read_very_eager()
    remote_conn.close()
    print(output.decode() + "\n")
开发者ID:jordanwimb,项目名称:kbpython,代码行数:15,代码来源:exercise2.py

示例8: TelnetRemoteConn

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
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"
开发者ID:pmusolino-rms,项目名称:Network-Automation-with-Python-and-Ansible-class,代码行数:47,代码来源:TelnetRemoteConn.py

示例9: Galil

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
class Galil(object):
    def __init__(self, ip, port):
        """A class which facilitates interaction with the galil controller"""

        self.con = Telnet(ip, port)

    def send_read(self, cmd):
        """Sends a galil command to the controller, then returns the result"""

        #First, we need to clear the input buffer, because we want to get rid of any previous strings
        try:
            self.con.read_very_eager()
        except:
            pass
        self.con.write( cmd+';')           # send the command string
        time.sleep(0.030)               # give some time for the galil to respond

        #get the response and strip off the garbage the galil sends to make interacting with it over telnet easier.
        return self.con.read_very_eager().rstrip(":").strip()

    def __optional(self, x_i):
        """Logic for commands with optional arguments."""
        return '' if x_i is None else chr(65+x_i)

    def __command(self, command, *args):
        """Sends commands and returns their results."""
        if len(args)==1: #all commands with optional axis specifiers
            args = map(self.__optional, args) #accept only one argument
        else: #all commands with two args start by specifiing the axis
            args = chr(65+args[0]), args[1] #which must be turned into a letter
        #print command.format(*args)
        return self.send_read(command.format(*args))

    def move_to(self, x_i, p):
        """Moves to the position p on axis x_i."""
        #print p
        #print self.__command("PA{}={}", x_i, p)
        #print self.begin_motion(x_i)
        return self.__command("PA{}={}", x_i, p)

    def move_steps(self, x_i, dp):
        """Moves the position dp steps on the axis x_i."""
        #print dp
        #print self.__command("PR{}={}", x_i, dp)
        #print self.begin_motion(x_i)
        return self.__command("PR{}={}", x_i, dp)

    def set_slewspeed(self, x_i, v):
        """Sets the slew speed of axis x_i to v."""
        return self.__command("SP{}={}", x_i, v)

    def set_jogspeed(self, x_i, v):
        """Sets the jogspeed of axis x_i to v."""
        return self.__command("JG{}={}", x_i, v)

    def get_position(self, x_i=None):
        """Returns the position of axis x_i.
        If x_i is None, returns a every position.
        The returned value is either an int or a tuple of ints."""
        x = self.__command("TP{}", x_i)
        #print x
        return eval(x)
    
    def begin_motion(self, x_i=None):
        """Begins motion on axis x_i.
        If x_i is None, motion begins on all axes."""
        return self.__command("BG{}", x_i)

    def in_motion(self, x_i):
        """Checks if axis x_i is in motion. returns a bool."""
        return bool(eval(self.__command("MG _BG{}", x_i)))

    def end_motion(self, x_i=None):
        """Stops motion on axis x_i.
        If x_i is None then motion is stopped on all axes."""
        return self.__command("ST{}", x_i)

    def motor_on(self, x_i=None):
        """Turns on the axis x_i.
        If x_i is None then all axes are turned on."""
        return self.__command("SH{}", x_i)

    def is_motor_on(self, x_i=0):
        """Returns True if axis x_i is on, else False."""
        return "0.0000" == self.__command("MG _MO{}", x_i)


    def motor_off(self, x_i=None):
        """Turns off the axis x_i.
        If x_i is None, then all axes are turned off."""
        return self.__command("MO{}", x_i)

    #THIS THING
    #It needs to be changed, for the sake of consistency.
    #I feel like it is something that should be moved,
    #and that this library should be only the lowest level
    #primatives for interacting with the galil.
    def scan(self, x_i, degrees, period, cycles):
        # max_accel = max_deccel = 1e6
        #initial_angle = 0
#.........这里部分代码省略.........
开发者ID:ChrisCalderon,项目名称:cofe-ground-operations,代码行数:103,代码来源:galil.py

示例10: getinfo

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
def getinfo(host):
    username = "admin"
    password = "admin"
    telnetTime = 5
    cmdTime = 3

    try:
        t = Telnet(host, timeout = telnetTime)
        #login
        t.read_until("username:", cmdTime)
        t.write(username + "\n")
        t.read_until("password:", cmdTime)
        t.write(password + "\n")

        #start exec cmd to get wifi info
        t.write("wlctl show\n")
        t.read_until("SSID", cmdTime)
        wifiStr = t.read_very_eager()

        #start exec cmd to get macaddree info
        t.write("lan show info\n")
        t.read_until("MACAddress", cmdTime)
        lanStr = t.read_very_eager()

        #close connection
        t.close()

        if len(wifiStr) > 0:
            
            #clear extra space
            wifiStr = "".join(wifiStr.split())
            wifiStr = wifiStr.decode('utf-8').encode('utf-8')
            #get SID KEY MAC
            ssid = wifiStr[1:wifiStr.find('QSS')]
            key = wifiStr[wifiStr.find('Key=') + 4:wifiStr.find('cmd')] if wifiStr.find('Key=') != -1 else '无密码'
            mac = lanStr[1:lanStr.find('__')].replace('\r\n','')

            currentTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

            try:
                cx = sqlite3.connect(sys.path[0]+"/TPLINKKEY.db")
                cx.text_factory = str
                cu = cx.cursor()
                cu.execute("select * from scanlog where ssid='%s' and key='%s'" % (ssid,key))
                if not cu.fetchone():
                    posData = getposition(host)
                    country = unicode(posData[0])
                    province = unicode(posData[1])
                    city = unicode(posData[2])
                    isp = unicode(posData[3])
                    cu.execute("insert into scanlog (host,mac,ssid,key,country,province,city,isp) values (?,?,?,?,?,?,?,?)", (host,mac,ssid,key,country,province,city,isp))
                    cx.commit()
                    print '[√] ['+currentTime +'] Found ' +host +'  '+ ssid +'  ' + key +' => Insert successly!'
                else:
                    print '[x] ['+currentTime +'] Found ' +host +'  '+ ssid +'  ' + key +' <= Found in database!'
                cu.close()
                cx.close()
            except Exception, e:
                print e
    except Exception,e:
        pass
开发者ID:kbdancer,项目名称:TPLINKKEY,代码行数:63,代码来源:telnetkey.py

示例11: ListenThread

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
class ListenThread( threading.Thread ):
    """ 
    This class is the heart of the programm. It takes care of polling the Fritzbox
    and listening for calls being signalled.
    """ 
    
    def __init__(self, parent, debugIt=False):
        """ 
        This function initializes pynotify and staring the polling thread.
        """ 
        self.parent = parent
        self.logger = parent.logger
        self.debugIt = debugIt
        
        self.logger.debug("Fritzbox Listener started")

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

            if self.counter == 15:

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

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

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

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

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

                        self.logger.debug("Connection lost")

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

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


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

                        # check MSN
                        self.ignore = False
                        self.msn = self.data_array[4]
                        if (MSN=="*" or MSN.find(self.msn) >= 0):
                            self.logger.info("number %s reports some activity" % (self.msn))
                        else:
                            self.logger.info("number %s reports some activity - and will be ignored" % (self.msn))
#.........这里部分代码省略.........
开发者ID:scareface972,项目名称:Umbheki,代码行数:103,代码来源:fritzbox.py

示例12: PttCon

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]

#.........这里部分代码省略.........

        # That bottom line shown could be assumed to be line 22 here because
        # for  multi-page articles the last line is definitely line 22 and no
        # need to do any string search
        bot_line = 22

        status_string = self.screen.display[23]
        while '100%' not in status_string:
            self.send_page_down(refresh=True)
            # erase last line
            self.get_data_and_feed(True, True, BIG5_MSG_ARTICLE_END_SIG)
            status_string = self.screen.display[23]

            bot_line_prev = bot_line
            #work around ptt name substitute warning
            while U_MSG_NAME_SUB_WARN in status_string:
                self.send_arrow_up()
                self.get_data_and_feed()
                self.write_like_human('\x0C')
                self.get_data_and_feed(True, True, BIG5_MSG_ARTICLE_END_SIG)
                status_string = self.screen.display[23]

            bot_line_start = status_string.find(u"~") + 1
            bot_line_end = status_string.find(U_MSG_LINE)
            bot_line = int(status_string[bot_line_start : bot_line_end])
            content_start = 23 - (bot_line - bot_line_prev)

            for i in range(content_start, 23):
                content = content + self.screen.display[i].rstrip() + '\n'

        # also strip trailing newline here
        content = content.rstrip('\n')

        # get aid and out
        # ptt and ptt2 display aid in different lines. Searching in buf would
        # be a lot easier.
        self.write_like_human('Q');
        self.get_data_and_feed()
        aid_off = self.buf.find(BIG5_MSG_AID)
        aid_off = self.buf.find('#', aid_off)
        aid = self.buf[aid_off : aid_off + AID_LEN]
        self.write_like_human(ENTER);
        self.get_data_and_feed(reset_screen=True)

        # create the article instance
        self.cur_article = PttArticle(topic, author, content, time_post, aid)

    def refresh_page(self, predecode=False):
    # TODO: add a last line(display[23]) non-empty detection?
        self.write_like_human('\x0C')
        self.get_data_and_feed(reset_screen=True, predecode=predecode)
        trial = 0
        while self.screen.display[23].strip() == u'':
            if trial > 2:
                break
            self.get_data_and_feed(reset_screen = False, predecode=predecode)
            trial = trial + 1

    def get_data_and_feed(self, reset_screen=False,
                          predecode=False, expect=None):
        if reset_screen:
            self.screen.reset()

        self.buf = self.tn.read_very_eager()
        t = 0
        while self.buf == '' or expect != None and expect not in self.buf:
        #FIXME: Add timeout here
            if t > 5:
                break
            time.sleep(1)
            self.buf = self.buf + self.tn.read_very_eager()
            t = t + 1

        if predecode:
            self.buf_predecode_half_esc()
        self.stream.feed(self.buf)

    def buf_predecode_half_esc(self, keep_esc=False):
        while True:
            try:
                self.buf.decode('big5hkscs')
                break
            except UnicodeDecodeError as ue:
                if self.buf[ue.end - 1] != '\x1b':
                    break
                c = self.buf[ue.start:].find('m')
                if c == -1:
                    break

                merged_char = self.buf[ue.start] + self.buf[ue.start + c + 1]
                esc_seq_str = self.buf[ue.end - 1:ue.start + c + 1]
                rest_str = self.buf[ue.start + c + 2:]
                self.buf = self.buf[:ue.start] + merged_char
                if keep_esc:
                    self.buf = self.buf + esc_seq_str
                self.buf = self.buf + rest_str

    def print_screen(self):
        for i in range(24):
            print self.screen.display[i]
开发者ID:rogerable,项目名称:ptt_article_dump,代码行数:104,代码来源:ptt_article_dump.py

示例13: Crawler

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
class Crawler(object):
    convert = Conv()

    def __init__(self, host, board_name, skip_existing):
        self.host = host
        self.delay = 0
        self.conn = Telnet(host, 3456)
        self.screen = pyte.Screen(80, 24)
        self.stream = pyte.Stream()
        self.screen.mode.discard(pyte.modes.LNM)
        self.stream.attach(self.screen)
        self.display
        self.login()
        self.display
        print(self.screen_shot)
        self.skip_existing = skip_existing
        self.board_name = board_name
        self.enter_board(board_name)
        print(self.screen_shot)
        for i in range(
                int(input('n - ' + self.last_id + ': ')),
                int(self.last_id) + 1):
            self.get_article(i)

    @property
    def display(self):
        s = self.conn.read_very_eager()
        while not s:
            s = self.conn.read_very_eager()
            time.sleep(self.delay)
        s = self.convert.conv(s)
        self.stream.feed(s.decode('utf-8'))
        return self.screen_shot

    @property
    def screen_shot(self):
        return "\n".join(self.screen.display)

    def close(self):
        self.conn.close()

    def send_enter(self, count=1):
        for i in range(count):
            s = self.send(b'\r')
            if count == 1:
                return s

    def send(self, s):
        self.conn.write(s)
        ret = self.display
        return ret

    def login(self):
        username = b'guest'
        self.conn.write(username + b'\r')
        self.conn.write(b'\rYY\r')
        self.send_enter(4)

    def enter_board(self, board):
        '''
        Save current board name in self.board
        and lastest article_id in self.last_id
        '''
        self.send('s{}\r'.format(board).encode('utf8'))
        print(self.screen_shot)
        time.sleep(1)
        while '(Tab/z)' not in self.screen_shot:
            self.send(b'\r')
            time.sleep(1)
        print(self.screen_shot)
        line = self.screen.cursor.y
        self.last_id = re.search(r'(?P<last_id>^\d+) ',
                                 self.screen.display[line].strip()).group()
        self.board = board

    def get_article(self, num=None):
        if not num:
            return

        root_dir = os.path.join('articles', self.board_name)
        mkdir_p(root_dir)
        path = os.path.join(root_dir, str(num))

        if self.skip_existing and os.path.exists(path):
            return

        print('try get %d' % num)
        self.send('{}\r\r'.format(num).encode('utf8'))
        if '(Tab/z)' in self.screen_shot:
            return
        raw_artcle = self.screen.display[:-1]

        status_line = self.screen.display[-1]
        if 'p%' not in status_line:
            return
        if status_line.find('[Y/n]') != -1:
            self.send(b'n')
        while status_line.find('(100%)') == -1:
            self.send(b'OB')
            status_line = self.screen.display[-1]
#.........这里部分代码省略.........
开发者ID:shaform,项目名称:bs2-crawler,代码行数:103,代码来源:crawler.py

示例14: Crawler

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]
class Crawler(object):
    convert = Bsdconv("ansi-control,byte:big5-defrag:byte,ansi-control|skip,big5:utf-8,bsdconv_raw")

    def __init__(self, host):
        self.host = host
        self.delay = 0
        self.conn = Telnet(host, 3456)
        self.screen = pyte.Screen(80, 24)
        self.stream = pyte.Stream()
        self.screen.mode.discard(pyte.modes.LNM)
        self.stream.attach(self.screen)
        self.display
        self.login()
        self.enter_board('NCTU-Teacher')
        for i in range(input('n - ' + self.last_id + ': '), int(self.last_id) + 1):
            self.get_article(i)

    @property
    def display(self):
        s = self.conn.read_very_eager()
        while not s:
            s = self.conn.read_very_eager()
            time.sleep(self.delay)           
        s = self.convert.conv(s)
        self.stream.feed(s.decode('utf-8'))
        return self.screen_shot

    @property
    def screen_shot(self):
        return "\n".join(self.screen.display).encode("utf-8")

    def close(self):
        self.conn.close()

    def send_enter(self, count=1):
        for i in range(count):
            s = self.send('\r')
            if count == 1:
                return s
    
    def send(self, s):
        self.conn.write(s)
        ret = self.display
        return ret

    def login(self):
        username = 'guest'
        self.conn.write(username + '\r')
        self.conn.write('\rYY\r')
        self.send_enter(2)

    def enter_board(self, board):
        '''
        Save current board name in self.board
        and lastest article_id in self.last_id
        '''
        self.send('OBOC')
        self.send('s{}'.format(board))
        self.send_enter(2)
        line = self.screen.cursor.y
        self.last_id = re.search(r'(?P<last_id>^\d+) ', self.screen.display[line].strip()).group()
        self.board = board

    def get_article(self, num=None):
        if not num:
            return

        self.send('{}\rOC'.format(num))
        raw_artcle = self.screen.display[:-1]

        status_line = self.screen.display[-1]
        if status_line.find('[Y/n]') != -1:
            self.send('n')
        while status_line.find('(100%)') == -1:
            self.send('OB')
            status_line = self.screen.display[-1]
            raw_artcle.append(self.screen.display[-2])
        self.save_article(num, raw_artcle)

    def term_comm(feed=None, wait=None):
        if feed != None:
            self.conn.write(feed)
            if wait:
                s = self.conn.read_some()
                s = self.convert.conv_chunk(s)
                self.stream.feed(s.decode("utf-8"))
        if wait != False:
            time.sleep(0.1)
            s = self.conn.read_very_eager()
            s = self.convert.conv_chunk(s)
            self.stream.feed(s.decode("utf-8"))
        ret = "\n".join(self.screen.display).encode("utf-8")
        return ret

    def save_article(self, num, content):
        '''
        :param content: a list get from screen
        '''
        chinese_keyword = {
            'board': '看板',
#.........这里部分代码省略.........
开发者ID:iblis17,项目名称:bs2-crawler,代码行数:103,代码来源:crawler.py

示例15: Node

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_very_eager [as 别名]

#.........这里部分代码省略.........
        else:
            address = self.ip

        return self.createKey(address, self.port)

    def __str__(self):
        return self.sockName()

    def isXDREnabled(self):
        config = self.infoGetConfig('xdr')
        if isinstance(config, Exception):
            return False


        xdr_enabled = config['xdr']['enable-xdr']
        return xdr_enabled == 'true'

    @return_exceptions
    @util.cached
    def _infoTelnet(self, command, port = None):
        # TODO: Handle socket failures
        if port == None:
            port = self.port
        try:
            self.sock == self.sock # does self.sock exist?
        except:
            self.sock = Telnet(self.ip, port)

        self.sock.write("%s\n"%command)

        starttime = time()
        result = ""
        while not result:
            result = self.sock.read_very_eager().strip()
            if starttime + self._timeout < time():
                # TODO: rasie appropriate exception
                raise IOError("Could not connect to node %s"%self.ip)
        return result

    @return_exceptions
    @util.cached
    def _infoCInfo(self, command, port = None):
        # TODO: citrusleaf.py does not support passing a timeout default is 0.5s
        if port == None:
            port = self.port

        result = citrusleaf.citrusleaf_info(self.ip, port, command
                                            , user=self.user
                                            , password=self.password)
        if result != -1 and result is not None:
            return result
        else:
            raise IOError(
                "Invalid command or Could not connect to node %s "%self.ip)

    @return_exceptions
    def info(self, command):
        """
        asinfo function equivalent

        Arguments:
        command -- the info command to execute on this node
        """
        if self._use_telnet:
            return self._infoTelnet(command)
        else:
开发者ID:PavanGupta01,项目名称:aerospike-admin,代码行数:70,代码来源:node.py


注:本文中的telnetlib.Telnet.read_very_eager方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。