'Function that reads channel until pattern is detected.
pattern takes a regular expression.
By default pattern will be self.base_prompt
Note: this currently reads beyond pattern. In the case of SSH it reads MAX_BUFFER.
In the case of telnet it reads all non-blocking data.
There are dependencies here like determining whether in config_mode that are actually
depending on reading beyond pattern.'

def _read_channel_expect(self, pattern=u'', re_flags=0, max_loops=None):

    output = u''
    if (not pattern):
        pattern = re.escape(self.base_prompt)
    log.debug(u'Pattern    is:    {0}'.format(pattern))
    i = 1
    loop_delay = 0.1
    if (not max_loops):
        max_loops = (self.timeout / loop_delay)
    while (i < max_loops):
        if (self.protocol == u'ssh'):
            try:
                self._lock_netmiko_session()
                new_data = self.remote_conn.recv(MAX_BUFFER)
                if (len(new_data) == 0):
                    raise EOFError(u'Channel    stream    closed    by    remote    device.')
                new_data = new_data.decode(u'utf-8', u'ignore')
                log.debug(u'_read_channel_expect    read_data:    {0}'.format(new_data))
                output += new_data
            except socket.timeout:
                raise NetMikoTimeoutException(u'Timed-out    reading    channel,    data    not    available.')
            finally:
                self._unlock_netmiko_session()
        elif (self.protocol == u'telnet'):
            output += self.read_channel()
        if re.search(pattern, output, flags=re_flags):
            log.debug(u'Pattern    found:    {0}    {1}'.format(pattern, output))
            return output
        time.sleep((loop_delay * self.global_delay_factor))
        i += 1
    raise NetMikoTimeoutException(u'Timed-out    reading    channel,    pattern    not    found    in    output:    {}'.format(pattern))
