Python telnetlib.Telnet() Examples

The following are 30 code examples of telnetlib.Telnet(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module telnetlib , or try the search function .
Example #1
Source File: pyboard.py    From ampy with MIT License 11 votes vote down vote up
def __init__(self, ip, user, password, read_timeout=None):
        import telnetlib
        self.tn = telnetlib.Telnet(ip, timeout=15)
        self.read_timeout = read_timeout
        if b'Login as:' in self.tn.read_until(b'Login as:', timeout=read_timeout):
            self.tn.write(bytes(user, 'ascii') + b"\r\n")

            if b'Password:' in self.tn.read_until(b'Password:', timeout=read_timeout):
                # needed because of internal implementation details of the telnet server
                time.sleep(0.2)
                self.tn.write(bytes(password, 'ascii') + b"\r\n")

                if b'for more information.' in self.tn.read_until(b'Type "help()" for more information.', timeout=read_timeout):
                    # login succesful
                    from collections import deque
                    self.fifo = deque()
                    return

        raise PyboardError('Failed to establish a telnet connection with the board') 
Example #2
Source File: telnet.py    From flashre with GNU Lesser General Public License v3.0 7 votes vote down vote up
def interactive(self):
        """
        Mimic an interctive session.
        """

        # Get the Telnet prompt
        prompt = self.wait_for_prompt()
        sys.stdout.write("%s" % prompt)

        while True:

            command = sys.stdin.readline().strip()

            # Fake command that ease quitting the interactive session
            if command == "exit":
                break

            self.send_command(command)
            data = self.recv_command()
            sys.stdout.write(data) 
Example #3
Source File: test_telnetlib.py    From BinderFilter with MIT License 7 votes vote down vote up
def test_SB_commands(self):
        # RFC 855, subnegotiations portion
        send = [tl.IAC + tl.SB + tl.IAC + tl.SE,
                tl.IAC + tl.SB + tl.IAC + tl.IAC + tl.IAC + tl.SE,
                tl.IAC + tl.SB + tl.IAC + tl.IAC + 'aa' + tl.IAC + tl.SE,
                tl.IAC + tl.SB + 'bb' + tl.IAC + tl.IAC + tl.IAC + tl.SE,
                tl.IAC + tl.SB + 'cc' + tl.IAC + tl.IAC + 'dd' + tl.IAC + tl.SE,
                EOF_sigil,
               ]
        self.dataq.put(send)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        nego = nego_collector(telnet.read_sb_data)
        telnet.set_option_negotiation_callback(nego.do_nego)
        txt = telnet.read_all()
        self.assertEqual(txt, '')
        want_sb_data = tl.IAC + tl.IAC + 'aabb' + tl.IAC + 'cc' + tl.IAC + 'dd'
        self.assertEqual(nego.sb_seen, want_sb_data)
        self.assertEqual('', telnet.read_sb_data())
        nego.sb_getter = None # break the nego => telnet cycle 
Example #4
Source File: connection_debug.py    From fermentrack with MIT License 6 votes vote down vote up
def test_telnet(hostname, port):
    # This attempts to test the validity of a controller
    # It returns a tuple (probably not the best way to do this) which is in the format:
    # Initial Connection Test (bool), Version Response Test (bool), Version Response (str)
    try:
        tn = telnetlib.Telnet(host=hostname, port=port, timeout=3)
    except socket.timeout:
        return False, False, None
    except ConnectionRefusedError:
        return False, False, None

    try:
        tn.write("n\r\n")
        version_string = tn.read_until("}",3)
    except:
        return True, False, None
    return True, True, version_string


# The following was used for testing during development 
Example #5
Source File: test_telnetlib.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_read_lazy_A(self):
        want = ['x' * 100, EOF_sigil]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        time.sleep(self.block_short)
        self.assertEqual('', telnet.read_lazy())
        data = ''
        while True:
            try:
                read_data = telnet.read_lazy()
                data += read_data
                if not read_data:
                    telnet.fill_rawq()
            except EOFError:
                break
            self.assertTrue(want[0].startswith(data))
        self.assertEqual(data, want[0]) 
Example #6
Source File: test_telnetlib.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_read_very_lazy_A(self):
        want = ['x' * 100, EOF_sigil]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        time.sleep(self.block_short)
        self.assertEqual('', telnet.read_very_lazy())
        data = ''
        while True:
            try:
                read_data = telnet.read_very_lazy()
            except EOFError:
                break
            data += read_data
            if not read_data:
                telnet.fill_rawq()
                self.assertEqual('', telnet.cookedq)
                telnet.process_rawq()
            self.assertTrue(want[0].startswith(data))
        self.assertEqual(data, want[0]) 
Example #7
Source File: test_telnetlib.py    From BinderFilter with MIT License 6 votes vote down vote up
def _test_command(self, data):
        """ helper for testing IAC + cmd """
        self.setUp()
        self.dataq.put(data)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        nego = nego_collector()
        telnet.set_option_negotiation_callback(nego.do_nego)
        txt = telnet.read_all()
        cmd = nego.seen
        self.assertTrue(len(cmd) > 0) # we expect at least one command
        self.assertIn(cmd[0], self.cmds)
        self.assertEqual(cmd[1], tl.NOOPT)
        self.assertEqual(len(''.join(data[:-1])), len(txt + cmd))
        nego.sb_getter = None # break the nego => telnet cycle
        self.tearDown() 
Example #8
Source File: test_telnetlib.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_read_very_lazy_A(self):
        want = ['x' * 100, EOF_sigil]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        time.sleep(self.block_short)
        self.assertEqual('', telnet.read_very_lazy())
        data = ''
        while True:
            try:
                read_data = telnet.read_very_lazy()
            except EOFError:
                break
            data += read_data
            if not read_data:
                telnet.fill_rawq()
                self.assertEqual('', telnet.cookedq)
                telnet.process_rawq()
            self.assertTrue(want[0].startswith(data))
        self.assertEqual(data, want[0]) 
Example #9
Source File: test_telnetlib.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _test_command(self, data):
        """ helper for testing IAC + cmd """
        self.setUp()
        self.dataq.put(data)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        nego = nego_collector()
        telnet.set_option_negotiation_callback(nego.do_nego)
        txt = telnet.read_all()
        cmd = nego.seen
        self.assertTrue(len(cmd) > 0) # we expect at least one command
        self.assertIn(cmd[0], self.cmds)
        self.assertEqual(cmd[1], tl.NOOPT)
        self.assertEqual(len(''.join(data[:-1])), len(txt + cmd))
        nego.sb_getter = None # break the nego => telnet cycle
        self.tearDown() 
Example #10
Source File: test_telnetlib.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_read_lazy_A(self):
        want = ['x' * 100, EOF_sigil]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        time.sleep(self.block_short)
        self.assertEqual('', telnet.read_lazy())
        data = ''
        while True:
            try:
                read_data = telnet.read_lazy()
                data += read_data
                if not read_data:
                    telnet.fill_rawq()
            except EOFError:
                break
            self.assertTrue(want[0].startswith(data))
        self.assertEqual(data, want[0]) 
Example #11
Source File: test_telnetlib.py    From BinderFilter with MIT License 6 votes vote down vote up
def _test_read_any_eager_A(self, func_name):
        """
        read_very_eager()
          Read all data available already queued or on the socket,
          without blocking.
        """
        want = [self.block_long, 'x' * 100, 'y' * 100, EOF_sigil]
        expects = want[1] + want[2]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        func = getattr(telnet, func_name)
        data = ''
        while True:
            try:
                data += func()
                self.assertTrue(expects.startswith(data))
            except EOFError:
                break
        self.assertEqual(expects, data) 
Example #12
Source File: tulpar.py    From tulpar with GNU General Public License v3.0 6 votes vote down vote up
def portScanner(url,dosyaAdi):
    raporIcerik=""
    baslangic=int(raw_input("Start port: "))
    bitis=int(raw_input("Finish port: "))
    for port in range(baslangic, bitis, 1):
        try:
            i=str(port)
            baglanti = telnetlib.Telnet(url, i)
            baglanti.write("\n")
            print "[+]", str(port), " - ", baglanti.read_all().splitlines()[0]
            raporIcerik+="[+]", str(port), " - ", baglanti.read_all().splitlines()[0]+"\n"
            baglanti.close()
        except:
            pass

    rapor = open(dosyaAdi, "a")
    rapor.write(raporIcerik)
    rapor.close() 
Example #13
Source File: test_telnetlib.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _test_read_any_eager_A(self, func_name):
        """
        read_very_eager()
          Read all data available already queued or on the socket,
          without blocking.
        """
        want = [self.block_long, 'x' * 100, 'y' * 100, EOF_sigil]
        expects = want[1] + want[2]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        func = getattr(telnet, func_name)
        data = ''
        while True:
            try:
                data += func()
                self.assertTrue(expects.startswith(data))
            except EOFError:
                break
        self.assertEqual(expects, data) 
Example #14
Source File: musicdata_lms.py    From pydPiper with MIT License 6 votes vote down vote up
def connectraw(self):
		# Try up to 10 times to connect to LMS
		connection_failed = 0
		self.rawserver = None

		logging.debug(u"Connecting to LMS raw service on {0}:{1}".format(self.server, self.port))
		while True:
			if connection_failed >= 10:
				logging.debug(u"Could not connect to raw LMS service")
				break
			try:
				# Connection to LMS
				self.rawserver = telnetlib.Telnet(self.server, self.port)

				# Subscribe to notification events that should wake up the system to collect data
				self.rawserver.write("subscribe pause,play,mixer,playlist\n".encode('ascii'))
				break
			except IOError:
				self.rawserver = None
				connection_failed += 1
				time.sleep(1)
		if self.rawserver is None:
			raise IOError(u"Could not connect raw to LMS") 
Example #15
Source File: telnet_scpi_client.py    From mobly with Apache License 2.0 6 votes vote down vote up
def cmd(self, cmd_str, wait_ret=True):
        if not isinstance(cmd_str, str):
            raise TypeError("Invalid command string", cmd_str)
        if not self.is_open:
            raise attenuator.Error("Telnet connection not open for commands")

        cmd_str.strip(self.tx_cmd_separator)
        self._tn.read_until(_ascii_string(self.prompt), 2)
        self._tn.write(_ascii_string(cmd_str + self.tx_cmd_separator))
        if wait_ret is False:
            return None

        match_idx, match_val, ret_text = self._tn.expect(
            [_ascii_string("\S+" + self.rx_cmd_separator)], 1)

        if match_idx == -1:
            raise attenuator.Error(
                "Telnet command failed to return valid data")

        ret_text = ret_text.decode()
        ret_text = ret_text.strip(self.tx_cmd_separator +
                                  self.rx_cmd_separator + self.prompt)

        return ret_text 
Example #16
Source File: telnet.py    From flashre with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, host):
        self.tlnt = telnetlib.Telnet(host, 23)

        # Announce that we will send strings character per character
        self.write_raw(telnetlib.IAC + telnetlib.WONT + telnetlib.LINEMODE) 
Example #17
Source File: test_telnetlib.py    From oss-ftp with MIT License 5 votes vote down vote up
def testTimeoutNone(self):
        # None, having other default
        self.assertTrue(socket.getdefaulttimeout() is None)
        socket.setdefaulttimeout(30)
        try:
            telnet = telnetlib.Telnet(HOST, self.port, timeout=None)
        finally:
            socket.setdefaulttimeout(None)
        self.assertTrue(telnet.sock.gettimeout() is None)
        telnet.sock.close() 
Example #18
Source File: test_telnetlib.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_read_until_with_poll(self):
        """Use select.poll() to implement telnet.read_until()."""
        want = ['x' * 10, 'match', 'y' * 10, EOF_sigil]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        if not telnet._has_poll:
            raise unittest.SkipTest('select.poll() is required')
        telnet._has_poll = True
        self.dataq.join()
        data = telnet.read_until('match')
        self.assertEqual(data, ''.join(want[:-2])) 
Example #19
Source File: test_telnetlib.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_read_until_with_select(self):
        """Use select.select() to implement telnet.read_until()."""
        want = ['x' * 10, 'match', 'y' * 10, EOF_sigil]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        telnet._has_poll = False
        self.dataq.join()
        data = telnet.read_until('match')
        self.assertEqual(data, ''.join(want[:-2])) 
Example #20
Source File: test_telnetlib.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_read_all_A(self):
        """
        read_all()
          Read all data until EOF; may block.
        """
        want = ['x' * 500, 'y' * 500, 'z' * 500, EOF_sigil]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        data = telnet.read_all()
        self.assertEqual(data, ''.join(want[:-1]))
        return 
Example #21
Source File: test_telnetlib.py    From oss-ftp with MIT License 5 votes vote down vote up
def testBasic(self):
        # connects
        telnet = telnetlib.Telnet(HOST, self.port)
        telnet.sock.close() 
Example #22
Source File: contelnet.py    From mpfshell with MIT License 5 votes vote down vote up
def __init__(self, ip, user, password):
        ConBase.__init__(self)

        if sys.version_info < (3, 0):
            self.read = self.__read2
        else:
            self.read = self.__read3

        self.tn = telnetlib.Telnet(ip)

        if user == "":
            self.fifo = deque()
            return

        if b"Login as:" in self.tn.read_until(b"Login as:", timeout=5.0):
            self.tn.write(bytes(user.encode("ascii")) + b"\r\n")

            if b"Password:" in self.tn.read_until(b"Password:", timeout=5.0):

                # needed because of internal implementation details of the telnet server
                time.sleep(0.2)
                self.tn.write(bytes(password.encode("ascii")) + b"\r\n")

                if b"for more information." in self.tn.read_until(
                    b'Type "help()" for more information.', timeout=5.0
                ):
                    self.fifo = deque()
                    return

        raise ConError() 
Example #23
Source File: test_telnetlib.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_read_until_B(self):
        # test the timeout - it does NOT raise socket.timeout
        want = ['hello', self.block_long, 'not seen', EOF_sigil]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        data = telnet.read_until('not seen', self.block_short)
        self.assertEqual(data, want[0])
        self.assertEqual(telnet.read_all(), 'not seen') 
Example #24
Source File: test_telnetlib.py    From BinderFilter with MIT License 5 votes vote down vote up
def testTimeoutOpen(self):
        telnet = telnetlib.Telnet()
        telnet.open(HOST, self.port, timeout=30)
        self.assertEqual(telnet.sock.gettimeout(), 30)
        telnet.sock.close() 
Example #25
Source File: test_telnetlib.py    From BinderFilter with MIT License 5 votes vote down vote up
def testTimeoutValue(self):
        telnet = telnetlib.Telnet(HOST, self.port, timeout=30)
        self.assertEqual(telnet.sock.gettimeout(), 30)
        telnet.sock.close() 
Example #26
Source File: test_telnetlib.py    From BinderFilter with MIT License 5 votes vote down vote up
def testTimeoutNone(self):
        # None, having other default
        self.assertTrue(socket.getdefaulttimeout() is None)
        socket.setdefaulttimeout(30)
        try:
            telnet = telnetlib.Telnet(HOST, self.port, timeout=None)
        finally:
            socket.setdefaulttimeout(None)
        self.assertTrue(telnet.sock.gettimeout() is None)
        telnet.sock.close() 
Example #27
Source File: test_telnetlib.py    From BinderFilter with MIT License 5 votes vote down vote up
def testTimeoutDefault(self):
        self.assertTrue(socket.getdefaulttimeout() is None)
        socket.setdefaulttimeout(30)
        try:
            telnet = telnetlib.Telnet(HOST, self.port)
        finally:
            socket.setdefaulttimeout(None)
        self.assertEqual(telnet.sock.gettimeout(), 30)
        telnet.sock.close() 
Example #28
Source File: test_telnetlib.py    From BinderFilter with MIT License 5 votes vote down vote up
def testBasic(self):
        # connects
        telnet = telnetlib.Telnet(HOST, self.port)
        telnet.sock.close() 
Example #29
Source File: musicdata_spop.py    From pydPiper with MIT License 5 votes vote down vote up
def connect(self):

		# Try up to 10 times to connect to REDIS
		self.connection_failed = 0
		self.dataclient = None

		logging.debug(u"Connecting to SPOP service on {0}:{1}".format(self.server, self.port))


		while True:
			if self.connection_failed >= 10:
				logging.debug(u"Could not connect to SPOP")
				break
			try:
				# Connection to MPD
				client = telnetlib.Telnet(self.server, self.port)
				client.read_until("\n")

				self.dataclient = client
				break
			except:
				self.dataclient = None
				self.connection_failed += 1
				time.sleep(1)
		if self.dataclient is None:
			raise IOError(u"Could not connect to SPOP")
		else:
			logging.debug(u"Connected to SPOP service") 
Example #30
Source File: test_telnetlib.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_read_until_B(self):
        # test the timeout - it does NOT raise socket.timeout
        want = ['hello', self.block_long, 'not seen', EOF_sigil]
        self.dataq.put(want)
        telnet = telnetlib.Telnet(HOST, self.port)
        self.dataq.join()
        data = telnet.read_until('not seen', self.block_short)
        self.assertEqual(data, want[0])
        self.assertEqual(telnet.read_all(), 'not seen')