faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 10 people (40%) answered Yes
Recently 3 of 9 people (33%) answered Yes

Entry

Telnet client for Win32

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 269, Adrian Eyre


"""
Packages: operating_systems.windows;networking.internet
"""
"""
> Text..., i would build a Tnet-Client similar the Linux console...
> I don't want to use the M$ telnet client :(
Okay. Win32/text based...
I assume you're after a non-line buffered input.
Try this. It's not quite right, but you can fiddle...
"""
# Dodgy telnet client for win32
# Portions of code snipped from Python-1.5.2/Demo/sockets/telnet.py
import msvcrt, socket, select, sys
IAC  = chr(255)	# Interpret as command
DONT = chr(254)
DO   = chr(253)
WONT = chr(252)
WILL = chr(251)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect("myhost", 23)
iac = 0
opt = ""
while 1:
	rl, wl, xl = [s],[],[]
	rl, wl, xl = select.select(rl, wl, xl, 0.1)
	if rl:
		c = s.recv(1)
		if not c:
			break
		cleandata = ""
		if opt:
			print ord(c)
			s.send(opt + c)
			opt = ''
		elif iac:
			iac = 0
			if c == IAC:
				cleandata = cleandata + c
			elif c in (DO, DONT):
				if c == DO: print '(DO)',
				else: print '(DONT)',
				opt = IAC + WONT
			elif c in (WILL, WONT):
				if c == WILL: print '(WILL)',
				else: print '(WONT)',
				opt = IAC + DONT
			else:
				print '(command)', ord(c)
		elif c == IAC:
			iac = 1
			print '(IAC)',
		else:
			cleandata = cleandata + c
		sys.stdout.write(c)
	if msvcrt.kbhit():
		c = msvcrt.getch()
		s.send(c)
		sys.stdout.write(c)