Beispiel #1
0
def listen_forever(
    callsign: str, callback: Callable[[str, str, float, str, int, str], None]
) -> asyncio.AbstractEventLoop:
    """Begin listening for events coming in from the Reverse Beacon Network

    Args:
        callsign (str): Your (or the user's) callsign
        callback (Callable[[spotter: str, spotted: str, frequency: float, mode: str, strength: int, timecode: str], None]): Callback function
    """

    # Get the event loop
    loop = asyncio.get_event_loop()

    # Coroutines for each Telnet server
    RBN_LOGGER.debug("Opening telnet connections")
    cw_coro = telnetlib3.open_connection(
        'telnet.reversebeacon.net',
        7000,
        shell=lambda r, w: telnet_handler(r, w, callsign, callback))
    ft8_coro = telnetlib3.open_connection(
        'telnet.reversebeacon.net',
        7001,
        shell=lambda r, w: telnet_handler(r, w, callsign, callback))

    # Register with the event loop
    RBN_LOGGER.debug("Begining event loop")
    reader, writer = loop.run_until_complete(cw_coro)
    reader, writer = loop.run_until_complete(ft8_coro)
    loop.run_until_complete(writer.protocol.waiter_closed)

    return loop
Beispiel #2
0
def test_telnet_server_reject_environ(event_loop, bind_host,
                                      unused_tcp_port):
    """Test Client's callback method send_environ() for specific requests."""
    from telnetlib3.telopt import SB, NEW_ENVIRON
    # given
    given_cols = 19
    given_rows = 84
    given_encoding = 'cp437'
    given_term = 'vt220'

    class ServerTestEnviron(telnetlib3.TelnetServer):
        def on_request_environ(self):
            return None

    yield from telnetlib3.create_server(
        protocol_factory=ServerTestEnviron,
        host=bind_host, port=unused_tcp_port,
        loop=event_loop)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        cols=given_cols, rows=given_rows, encoding=given_encoding,
        term=given_term, connect_minwait=0.05, connect_maxwait=0.05)

    # this causes the client to expect the server to have demanded environment
    # values, since it did, of course demand DO NEW_ENVIRON! However, our API
    # choice here has chosen not to -- the client then indicates this as a
    # failed sub-negotiation (SB + NEW_ENVIRON).
    _failed = {key: val for key, val in writer.pending_option.items() if val}
    assert _failed == {SB + NEW_ENVIRON: True}
Beispiel #3
0
def test_telnet_client_send_xdisploc(event_loop, bind_host, unused_tcp_port):
    """Test Client's callback method send_xdisploc()."""
    # given
    _waiter = asyncio.Future()
    given_xdisploc = 'alpha'

    class ServerTestXdisploc(telnetlib3.TelnetServer):
        def on_xdisploc(self, xdisploc):
            super().on_xdisploc(xdisploc)
            _waiter.set_result(xdisploc)

        def begin_advanced_negotiation(self):
            from telnetlib3.telopt import DO, XDISPLOC
            super().begin_advanced_negotiation()
            self.writer.iac(DO, XDISPLOC)

    yield from telnetlib3.create_server(protocol_factory=ServerTestXdisploc,
                                        host=bind_host,
                                        port=unused_tcp_port,
                                        loop=event_loop)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host,
        port=unused_tcp_port,
        loop=event_loop,
        xdisploc=given_xdisploc,
        connect_minwait=0.05)

    recv_xdisploc = yield from asyncio.wait_for(_waiter, 0.5)
    assert recv_xdisploc == given_xdisploc
Beispiel #4
0
def test_telnet_client_send_tspeed(event_loop, bind_host, unused_tcp_port):
    """Test Client's callback method send_tspeed()."""
    # given
    _waiter = asyncio.Future()
    given_rx, given_tx = 1337, 1919

    class ServerTestTspeed(telnetlib3.TelnetServer):
        def on_tspeed(self, rx, tx):
            super().on_tspeed(rx, tx)
            _waiter.set_result((rx, tx))

        def begin_advanced_negotiation(self):
            from telnetlib3.telopt import DO, TSPEED
            super().begin_advanced_negotiation()
            self.writer.iac(DO, TSPEED)

    yield from telnetlib3.create_server(protocol_factory=ServerTestTspeed,
                                        host=bind_host,
                                        port=unused_tcp_port,
                                        loop=event_loop)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host,
        port=unused_tcp_port,
        loop=event_loop,
        tspeed=(given_rx, given_tx),
        connect_minwait=0.05)

    recv_rx, recv_tx = yield from asyncio.wait_for(_waiter, 0.5)
    assert recv_rx == given_rx
    assert recv_tx == given_tx
Beispiel #5
0
def test_send_iac_dont_dont(event_loop, bind_host, unused_tcp_port):
    """Try a DONT and ensure it cannot be sent twice."""
    from telnetlib3.telopt import DONT, ECHO
    _waiter = asyncio.Future()

    yield from telnetlib3.create_server(
        protocol_factory=telnetlib3.BaseServer, host=bind_host,
        port=unused_tcp_port, loop=event_loop, connect_maxwait=0.05,
        _waiter_connected=_waiter)

    _, client_writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        connect_minwait=0.05)

    # say it once,
    result = client_writer.iac(DONT, ECHO)
    assert result == True

    # say it again, suppressed
    result = client_writer.iac(DONT, ECHO)
    assert result == False

    server_writer = (yield from asyncio.wait_for(_waiter, 0.5)).writer

    assert client_writer.remote_option[ECHO] is False
    assert server_writer.local_option[ECHO] is False
Beispiel #6
0
def test_telnet_client_send_naws(event_loop, bind_host, unused_tcp_port):
    """Test Client's NAWS of callback method send_naws()."""
    # given a server
    _waiter = asyncio.Future()
    given_cols, given_rows = 40, 20

    class ServerTestNaws(telnetlib3.TelnetServer):
        def on_naws(self, width, height):
            super().on_naws(width, height)
            _waiter.set_result((height, width))

    yield from telnetlib3.create_server(protocol_factory=ServerTestNaws,
                                        host=bind_host,
                                        port=unused_tcp_port,
                                        loop=event_loop,
                                        connect_maxwait=0.05)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host,
        port=unused_tcp_port,
        loop=event_loop,
        cols=given_cols,
        rows=given_rows,
        connect_minwait=0.05)

    recv_cols, recv_rows = yield from asyncio.wait_for(_waiter, 0.5)
    assert recv_cols == given_cols
    assert recv_rows == given_rows
Beispiel #7
0
def test_telnet_client_no_charset(event_loop, bind_host, unused_tcp_port):
    """Test Client's callback method send_charset() does not select."""
    # given
    _waiter = asyncio.Future()

    class ServerTestCharset(telnetlib3.TelnetServer):
        def on_request_charset(self):
            return ['illegal', 'this-is-no-good-either']

    class ClientTestCharset(telnetlib3.TelnetClient):
        def send_charset(self, offered):
            selected = super().send_charset(offered)
            _waiter.set_result(selected)
            return selected

    yield from telnetlib3.create_server(protocol_factory=ServerTestCharset,
                                        host=bind_host,
                                        port=unused_tcp_port,
                                        loop=event_loop)

    reader, writer = yield from telnetlib3.open_connection(
        client_factory=ClientTestCharset,
        host=bind_host,
        port=unused_tcp_port,
        loop=event_loop,
        encoding='latin1',
        connect_minwait=0.05)

    # charset remains latin1
    val = yield from asyncio.wait_for(_waiter, 0.5)
    assert val == ''
    assert writer.get_extra_info('charset') == 'latin1'
Beispiel #8
0
async def test_telnet_client_negotiation_fail(
        event_loop, bind_host, unused_tcp_port):
    """Test telnetlib3.TelnetCLient() negotiation failure with server."""

    class ClientNegotiationFail(telnetlib3.TelnetClient):
        def connection_made(self, transport):
            from telnetlib3.telopt import WILL, TTYPE
            super().connection_made(transport)
            # this creates a pending negotiation demand from the client-side.
            self.writer.iac(WILL, TTYPE)

    # a server that never responds with nothing.
    await event_loop.create_server(asyncio.Protocol,
                                        bind_host, unused_tcp_port)

    given_minwait = 0.05
    given_maxwait = 0.100

    stime = time.time()
    reader, writer = await asyncio.wait_for(telnetlib3.open_connection(
        client_factory=ClientNegotiationFail, host=bind_host,
        port=unused_tcp_port,
        connect_minwait=given_minwait,
        connect_maxwait=given_maxwait), 5)

    elapsed_ms = int((time.time() - stime) * 1e3)
    expected_ms = int(given_maxwait * 1e3)
    assert expected_ms <= elapsed_ms <= expected_ms + 50
def test_telnet_client_and_server_escape_iac_binary(event_loop, bind_host,
                                                    unused_tcp_port):
    """Ensure that IAC (byte 255) may be sent across the wire in binary."""
    # given
    _waiter = asyncio.Future()
    given_string = bytes(range(256)) * 2

    yield from telnetlib3.create_server(host=bind_host,
                                        port=unused_tcp_port,
                                        _waiter_connected=_waiter,
                                        loop=event_loop,
                                        encoding=False,
                                        connect_maxwait=0.05)

    client_reader, client_writer = yield from telnetlib3.open_connection(
        host=bind_host,
        port=unused_tcp_port,
        loop=event_loop,
        encoding=False,
        connect_minwait=0.05)

    server = yield from asyncio.wait_for(_waiter, 0.5)

    server.writer.write(given_string)
    result = yield from client_reader.read(len(given_string))
    assert result == given_string
    server.writer.close()
    eof = yield from asyncio.wait_for(client_reader.read(), 0.5)
    assert eof == b''
Beispiel #10
0
def test_telnet_client_and_server_encoding_bidirectional(
        event_loop, bind_host, unused_tcp_port):
    """Given a default encoding for client and server, client always wins!"""
    # given
    _waiter = asyncio.Future()

    yield from telnetlib3.create_server(host=bind_host,
                                        port=unused_tcp_port,
                                        _waiter_connected=_waiter,
                                        loop=event_loop,
                                        encoding='latin1',
                                        connect_maxwait=0.05)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host,
        port=unused_tcp_port,
        loop=event_loop,
        encoding='cp437',
        connect_minwait=0.05)

    srv_instance = yield from asyncio.wait_for(_waiter, 0.5)

    assert srv_instance.encoding(incoming=True) == 'cp437'
    assert srv_instance.encoding(outgoing=True) == 'cp437'
    assert srv_instance.encoding(incoming=True, outgoing=True) == 'cp437'
    assert writer.protocol.encoding(incoming=True) == 'cp437'
    assert writer.protocol.encoding(outgoing=True) == 'cp437'
    assert writer.protocol.encoding(incoming=True, outgoing=True) == 'cp437'
Beispiel #11
0
async def test_telnet_client_send_charset(event_loop, bind_host, unused_tcp_port):
    """Test Client's callback method send_charset() selection for illegals."""
    # given
    _waiter = asyncio.Future()

    class ServerTestCharset(telnetlib3.TelnetServer):
        def on_request_charset(self):
            return ['illegal', 'cp437']

    class ClientTestCharset(telnetlib3.TelnetClient):
        def send_charset(self, offered):
            selected = super().send_charset(offered)
            _waiter.set_result(selected)
            return selected

    await asyncio.wait_for(
        telnetlib3.create_server(
            protocol_factory=ServerTestCharset,
            host=bind_host, port=unused_tcp_port,
            loop=event_loop),
        0.15)

    reader, writer = await asyncio.wait_for(
        telnetlib3.open_connection(
            client_factory=ClientTestCharset,
            host=bind_host, port=unused_tcp_port, loop=event_loop,
            encoding='latin1', connect_minwait=0.05),
        0.15)

    val = await asyncio.wait_for(_waiter, 1.5)
    assert val == 'cp437'
    assert writer.get_extra_info('charset') == 'cp437'
Beispiel #12
0
def test_telnet_client_send_environ(event_loop, bind_host,
                                    unused_tcp_port):
    """Test Client's callback method send_environ() for specific requests."""
    # given
    _waiter = asyncio.Future()
    given_cols = 19
    given_rows = 84
    given_encoding = 'cp437'
    given_term = 'vt220'

    class ServerTestEnviron(telnetlib3.TelnetServer):
        def on_environ(self, mapping):
            super().on_environ(mapping)
            _waiter.set_result(mapping)

    yield from telnetlib3.create_server(
        protocol_factory=ServerTestEnviron,
        host=bind_host, port=unused_tcp_port,
        loop=event_loop)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        cols=given_cols, rows=given_rows, encoding=given_encoding,
        term=given_term, connect_minwait=0.05)

    mapping = yield from asyncio.wait_for(_waiter, 0.5)
    assert mapping == {
        'COLUMNS': str(given_cols),
        'LANG': 'en_US.' + given_encoding,
        'LINES': str(given_rows),
        'TERM': 'vt220'
    }
Beispiel #13
0
def test_telnet_client_idle_duration_minwait(event_loop, bind_host,
                                             unused_tcp_port):
    """Exercise TelnetClient.idle property and minimum connection time."""
    from telnetlib3.telopt import IAC, WONT, TTYPE

    # a server that doesn't care
    yield from event_loop.create_server(asyncio.Protocol, bind_host,
                                        unused_tcp_port)

    given_minwait = 0.100

    stime = time.time()
    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host,
        port=unused_tcp_port,
        loop=event_loop,
        connect_minwait=given_minwait,
        connect_maxwait=given_minwait)

    elapsed_ms = int((time.time() - stime) * 1e3)
    expected_ms = int(given_minwait * 1e3)
    assert expected_ms <= elapsed_ms <= expected_ms + 50

    # verify
    assert 0 <= writer.protocol.idle <= 0.5
    assert 0 <= writer.protocol.duration <= 0.5
Beispiel #14
0
def test_telnet_reader_read_exactly_bytes(
        event_loop, bind_host, unused_tcp_port):
    """Ensure TelnetReader.readexactly, especially IncompleteReadError."""
    # given
    _waiter = asyncio.Future()
    given = string.ascii_letters.encode('ascii')
    given_partial = b'zzz'

    def shell(reader, writer):
        writer.write(given + given_partial)
        writer.close()

    yield from telnetlib3.create_server(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        connect_maxwait=0.05, shell=shell, encoding=False)

    client_reader, client_writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        connect_minwait=0.05, encoding=False)

    # exercise, readexactly # bytes of given
    result = yield from asyncio.wait_for(
        client_reader.readexactly(len(given)), 0.5)

    # verify,
    assert result == given

    # exercise, read 1 byte beyond given_partial
    given_readsize = len(given_partial) + 1
    with pytest.raises(asyncio.IncompleteReadError) as exc_info:
        result = yield from asyncio.wait_for(
            client_reader.readexactly(given_readsize), 0.5)

    assert exc_info.value.partial == given_partial
    assert exc_info.value.expected == given_readsize
Beispiel #15
0
def test_telnet_client_negotiation_fail(event_loop, bind_host,
                                        unused_tcp_port):
    """Test telnetlib3.TelnetCLient() negotiation failure with server."""
    class ClientNegotiationFail(telnetlib3.TelnetClient):
        def connection_made(self, transport):
            from telnetlib3.telopt import WILL, TTYPE
            super().connection_made(transport)
            # this creates a pending negotiation demand from the client-side.
            self.writer.iac(WILL, TTYPE)

    # a server that never responds with nothing.
    yield from event_loop.create_server(asyncio.Protocol, bind_host,
                                        unused_tcp_port)

    given_minwait = 0.05
    given_maxwait = 0.100

    stime = time.time()
    reader, writer = yield from asyncio.wait_for(
        telnetlib3.open_connection(client_factory=ClientNegotiationFail,
                                   host=bind_host,
                                   port=unused_tcp_port,
                                   connect_minwait=given_minwait,
                                   connect_maxwait=given_maxwait), 5)

    elapsed_ms = int((time.time() - stime) * 1e3)
    expected_ms = int(given_maxwait * 1e3)
    assert expected_ms <= elapsed_ms <= expected_ms + 50
Beispiel #16
0
def test_telnet_reader_read_beyond_limit_bytes(
        event_loop, bind_host, unused_tcp_port):
    """Ensure ability to read(-1) beyond segment sizes of reader._limit."""
    # given
    _waiter = asyncio.Future()

    limit = 10

    def shell(reader, writer):
        assert reader._limit == limit
        given = b'x' * (limit + 1)
        writer.write(given)
        writer.close()

    yield from telnetlib3.create_server(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        connect_maxwait=0.05, shell=shell, encoding=False, limit=limit)

    client_reader, client_writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        connect_minwait=0.05, encoding=False, limit=limit)

    assert client_reader._limit == limit
    value = yield from asyncio.wait_for(client_reader.read(), 0.5)
    assert value == b'x' * (limit + 1)
Beispiel #17
0
async def test_telnet_client_send_charset(event_loop, bind_host,
                                          unused_tcp_port):
    """Test Client's callback method send_charset() selection for illegals."""
    # given
    _waiter = asyncio.Future()

    class ServerTestCharset(telnetlib3.TelnetServer):
        def on_request_charset(self):
            return ['illegal', 'cp437']

    class ClientTestCharset(telnetlib3.TelnetClient):
        def send_charset(self, offered):
            selected = super().send_charset(offered)
            _waiter.set_result(selected)
            return selected

    await asyncio.wait_for(
        telnetlib3.create_server(protocol_factory=ServerTestCharset,
                                 host=bind_host,
                                 port=unused_tcp_port,
                                 loop=event_loop), 0.15)

    reader, writer = await asyncio.wait_for(
        telnetlib3.open_connection(client_factory=ClientTestCharset,
                                   host=bind_host,
                                   port=unused_tcp_port,
                                   loop=event_loop,
                                   encoding='latin1',
                                   connect_minwait=0.05), 0.15)

    val = await asyncio.wait_for(_waiter, 1.5)
    assert val == 'cp437'
    assert writer.get_extra_info('charset') == 'cp437'
    def main(self):
        loop = asyncio.get_event_loop()

        coro = telnetlib3.open_connection(self.server_ip, 23, shell=self.shell)
        reader, writer = loop.run_until_complete(coro)
        print('debut-fin')

        loop.run_until_complete(writer.protocol.waiter_closed)
        file_name = self.file_name
Beispiel #19
0
    def _telnet_connect(self):
        logger.debug("Connecting to GrandMA2...")
        self._telnet = telnetlib3.open_connection(
            self._config['grandma']['address'].get(),
            self._config['grandma']['port'].get(),
            shell=self._telnet_shell,
            log=logger
        )

        self._reader, self._writer = self.loop.run_until_complete(self._telnet)
Beispiel #20
0
def test_telnet_client_open_close_by_write(event_loop, bind_host,
                                           unused_tcp_port):
    """Exercise BaseClient.connection_lost() on writer closed."""
    yield from event_loop.create_server(asyncio.Protocol, bind_host,
                                        unused_tcp_port)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, connect_minwait=0.05)
    writer.close()
    assert (yield from reader.read()) == ''
Beispiel #21
0
 def do_step(self):
     # device, db, table):
     routine = CustomRoutine(self.group, self.dev_name, self.device,
                             self.db, self.sql_table, self.sql_table2)
     loop = asyncio.new_event_loop()
     asyncio.set_event_loop(loop)
     coro = telnetlib3.open_connection(self.telnet_addr,
                                       self.telnet_port,
                                       shell=routine.mesh_reader)
     reader, writer = loop.run_until_complete(coro)
     loop.run_until_complete(writer.protocol.waiter_closed)
     self.latest = str(
         datetime.datetime.now()) + " Async Routine Complete. "
Beispiel #22
0
def test_telnet_client_open_close_by_error(event_loop, bind_host,
                                           unused_tcp_port):
    """Exercise BaseClient.connection_lost() on error."""
    yield from event_loop.create_server(asyncio.Protocol, bind_host,
                                        unused_tcp_port)

    class GivenException(Exception):
        pass

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, connect_minwait=0.05)

    writer.protocol.connection_lost(GivenException("candy corn 4 everyone"))
    with pytest.raises(GivenException):
        yield from reader.read()
Beispiel #23
0
    async def connect(self):
        # https://telnetlib3.readthedocs.io/en/latest/intro.html
        # loop = asyncio.get_event_loop()
        # coro = telnetlib3.open_connection(self.telnet_host, self.telnet_port, shell=self.shell) # , loop=self.loop
        # https://stackoverflow.com/questions/36342899/asyncio-ensure-future-vs-baseeventloop-create-task-vs-simple-coroutine
        # https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future
        # https://stackoverflow.com/questions/28609534/python-asyncio-force-timeout
        #task = asyncio.ensure_future(coro)  # asyncio.create_task(coro())  #
        #reader, writer = loop.run_until_complete(asyncio.wait_for(task, 30))
        #reader, writer = self.loop.run_until_complete(coro)
        #self.loop.run_until_complete(writer.protocol.waiter_closed)
        tries = 0

        while (not await self.is_connected()
               and tries < self.connection_retries):
            tries += 1
            self._waiter_connected = self.loop.create_future(
            )  #asyncio.Future()
            self._waiter_closed = self.loop.create_future()  #asyncio.Future()
            # https://stackoverflow.com/questions/50678184/how-to-pass-additional-parameters-to-handle-client-coroutine
            # reader, writer = await telnetlib3.open_connection(self.telnet_host, self.telnet_port, shell=self.shell, loop=self.loop)

            try:
                #self.reader, self.writer = await telnetlib3.open_connection(self.host, self.port, loop=self.loop)
                self.reader, self.writer = await asyncio.shield(
                    asyncio.wait_for(telnetlib3.open_connection(
                        self.host,
                        self.port,
                        waiter_closed=self._waiter_closed,
                        _waiter_connected=self._waiter_connected,
                        loop=self.loop),
                                     self.connection_timeout,
                                     loop=self.loop))

            except asyncio.TimeoutError as e:
                #except Exception as e:
                # self._waiter_connected = None
                # self._waiter_closed = None
                logging.warning(
                    "Connection attempt {} timed out after {}s".format(
                        tries, self.connection_timeout))

            #await self.shell(self.reader, self.writer)
            # coro = telnetlib3.open_connection(self.telnet_host, self.telnet_port, shell=self.shell, loop=self.loop)
            # task = asyncio.ensure_future(coro)  # asyncio.create_task(coro())  #
            # reader, writer = await asyncio.wait({task}, loop = self.loop)

        return tries < self.connection_retries
Beispiel #24
0
def test_telnet_client_open_closed_by_peer(event_loop, bind_host,
                                           unused_tcp_port):
    """Exercise BaseClient.connection_lost()."""
    class DisconnecterProtocol(asyncio.Protocol):
        def connection_made(self, transport):
            # disconnect on connect
            transport.close()

    yield from event_loop.create_server(DisconnecterProtocol, bind_host,
                                        unused_tcp_port)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, connect_minwait=0.05)

    # read until EOF, no data received.
    data_received = yield from reader.read()
    assert data_received == ''
Beispiel #25
0
def test_telnet_client_shell_as_coroutine(event_loop, bind_host,
                                          unused_tcp_port):
    """Test callback shell(reader, writer) as coroutine of create_server()."""
    _waiter = asyncio.Future()

    @asyncio.coroutine
    def shell(reader, writer):
        _waiter.set_result(True)

    # a server that doesn't care
    yield from event_loop.create_server(asyncio.Protocol,
                                        bind_host, unused_tcp_port)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        shell=shell, connect_minwait=0.05)

    yield from asyncio.wait_for(_waiter, 0.5)
Beispiel #26
0
def test_open_connection(bind_host, unused_tcp_port):
    """Exercise telnetlib3.open_connection with default options."""
    _waiter = asyncio.Future()
    yield from telnetlib3.create_server(bind_host,
                                        unused_tcp_port,
                                        _waiter_connected=_waiter,
                                        connect_maxwait=0.05)
    client_reader, client_writer = yield from telnetlib3.open_connection(
        bind_host, unused_tcp_port, connect_minwait=0.05)
    server = yield from asyncio.wait_for(_waiter, 0.5)
    assert repr(server.writer) == (
        '<TelnetWriter server mode:kludge +lineflow -xon_any +slc_sim '
        'server-will:BINARY,ECHO,SGA '
        'client-will:BINARY,CHARSET,NAWS,NEW_ENVIRON,TTYPE>')
    assert repr(client_writer) == (
        '<TelnetWriter client mode:kludge +lineflow -xon_any +slc_sim '
        'client-will:BINARY,CHARSET,NAWS,NEW_ENVIRON,TTYPE '
        'server-will:BINARY,ECHO,SGA>')
Beispiel #27
0
    async def _connect(self):
        """Make Telnet connection."""
        try:
            open_future = telnetlib3.open_connection(self.host, self.port)
            self._reader, self._writer = await asyncio.wait_for(
                open_future, self.timeout)
        except Exception as error:
            raise error from error
        self._response_handler_task = asyncio.create_task(
            self._response_handler())
        self._state = const.STATE_CONNECTED
        self._command_queue_task = asyncio.create_task(
            self._process_command_queue())
        if self._heart_beat_interval is not None and self._heart_beat_interval > 0:
            self._heart_beat_task = asyncio.create_task(self._heart_beat())

        _LOGGER.debug("Connected to %s", self.host)
        self._avr.dispatcher.send(const.SIGNAL_TELNET_EVENT,
                                  const.EVENT_CONNECTED)
Beispiel #28
0
def test_telnet_client_send_var_uservar_environ(event_loop, bind_host,
                                                unused_tcp_port):
    """Test Client's callback method send_environ() for VAR/USERVAR request."""
    # given
    _waiter = asyncio.Future()
    given_cols = 19
    given_rows = 84
    given_encoding = 'cp437'
    given_term = 'vt220'

    class ServerTestEnviron(telnetlib3.TelnetServer):
        def on_environ(self, mapping):
            super().on_environ(mapping)
            _waiter.set_result(mapping)

        def on_request_environ(self):
            from telnetlib3.telopt import VAR, USERVAR
            return [VAR, USERVAR]

    yield from telnetlib3.create_server(
        protocol_factory=ServerTestEnviron,
        host=bind_host, port=unused_tcp_port,
        loop=event_loop)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        cols=given_cols, rows=given_rows, encoding=given_encoding,
        term=given_term, connect_minwait=0.05, connect_maxwait=0.05)

    mapping = yield from asyncio.wait_for(_waiter, 0.5)
    # although nothing was demanded by server,
    assert mapping == {}

    # the client still volunteered these basic variables,
    mapping == {
        'COLUMNS': str(given_cols),
        'LANG': 'en_US.' + given_encoding,
        'LINES': str(given_rows),
        'TERM': 'vt220'
    }
    for key, val in mapping.items():
        assert writer.get_extra_info(key) == val
Beispiel #29
0
def test_telnet_reader_using_readline_bytes(
        event_loop, bind_host, unused_tcp_port):
    """Ensure strict RFC interpretation of newlines in readline method."""
    # given
    _waiter = asyncio.Future()
    given_expected = {
        b'alpha\r\x00': b'alpha\r',
        b'bravo\r\n': b'bravo\r\n',
        b'charlie\n': b'charlie\n',
        b'---\r': b'---\r',
        b'---\r\n': b'---\r\n',
        b'\r\x00': b'\r',
        b'\n': b'\n',
        b'\r\n': b'\r\n',
        b'xxxxxxxxxxx': b'xxxxxxxxxxx',
    }

    def shell(reader, writer):
        for item in sorted(given_expected):
            writer.write(item)
        writer.close()

    yield from telnetlib3.create_server(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        connect_maxwait=0.05, shell=shell, encoding=False)

    client_reader, client_writer = yield from telnetlib3.open_connection(
        host=bind_host, port=unused_tcp_port, loop=event_loop,
        connect_minwait=0.05, encoding=False)

    # exercise,
    for given, expected in sorted(given_expected.items()):
        result = yield from asyncio.wait_for(client_reader.readline(), 0.5)

        # verify.
        assert result == expected

    # exercise,
    eof = yield from asyncio.wait_for(client_reader.read(), 0.5)

    # verify.
    assert eof == b''
Beispiel #30
0
    async def try_to_connect(self):

        # a little closure to capture our ip and expose it to the parser
        def client_factory():
            return TelnetClient(proxy=self, encoding='utf-8')

        await self.feedback('frisbee_status', "trying to telnet..")
        logger.info(f"Trying to telnet on {self.control_ip}")
        try:
            self._reader, self._writer = await asyncio.wait_for(
                telnetlib3.open_connection(
                    self.control_ip,
                    23,
                    shell=None,
                    log=logger,
                    connect_minwait=self.connect_minwait,
                    connect_maxwait=self.connect_maxwait),
                timeout=self.connect_timeout)
        except (asyncio.TimeoutError, OSError) as exc:
            self._reader, self._writer = None, None
        except Exception as exc:
            logger.exception(f"telnet connect: unexpected exception {exc}")
Beispiel #31
0
def test_telnet_client_encoding_default(event_loop, bind_host,
                                        unused_tcp_port):
    """Default encoding US-ASCII unless it can be negotiated/confirmed!"""
    from telnetlib3.telopt import IAC, WONT, TTYPE
    # given
    _waiter = asyncio.Future()

    yield from event_loop.create_server(asyncio.Protocol, bind_host,
                                        unused_tcp_port)

    reader, writer = yield from telnetlib3.open_connection(
        host=bind_host,
        port=unused_tcp_port,
        loop=event_loop,
        connect_minwait=0.05)

    # after MIN_CONNECT elapsed, client is in US-ASCII state.
    assert writer.protocol.encoding(incoming=True) == 'US-ASCII'
    assert writer.protocol.encoding(outgoing=True) == 'US-ASCII'
    assert writer.protocol.encoding(incoming=True, outgoing=True) == 'US-ASCII'
    with pytest.raises(TypeError):
        # at least one direction should be specified
        writer.protocol.encoding()
Beispiel #32
0
import asyncio, telnetlib3


@asyncio.coroutine
def shell(reader, writer):  #--shell=my_module.fn_shell
    while True:
        # read stream until found
        outp = yield from reader.read(1024)
        if not outp:
            # End of File
            break
        # Using API library xstatus with Tandberg system
        elif 'Password:'******'TANDBERGsys##01\r\nxstatus\r\n')

        print(outp, flush=True)

    print()


# Set the event loop to use
loop = asyncio.get_event_loop()

# Connect to a TCP Telnet server as a Telnet client
coro = telnetlib3.open_connection('10.50.18.143', 23, shell=shell)

# Blocking call which  returns when connecting is done
reader, writer = loop.run_until_complete(coro)

# Executing command
writer.protocol