Can anyone explain a part of a telnet client code to me..
Jia Lu
Roka100 at gmail.com
Sat Feb 10 22:48:57 EST 2007
Hello
I have a program that can telnet to a host.
But I cannot understand from [for c in data] part, can anyone explain
it to me?
Thank you very much.
[CODE]
import sys, posix, time
from socket import *
BUFSIZE = 1024
# Telnet protocol characters
IAC = chr(255) # Interpret as command
DONT = chr(254)
DO = chr(253)
WONT = chr(252)
WILL = chr(251)
def main():
# Get hostname from param
host = sys.argv[1]
try:
# Get ip from hostname
hostaddr = gethostbyname(host)
except error:
sys.stderr.write(sys.argv[1] + ': bad host name\n')
sys.exit(2)
# Check param[2] as type of protocol
if len(sys.argv) > 2:
servname = sys.argv[2]
else:
# default use telnet
servname = 'telnet'
# If got servname as port num
if '0' <= servname[:1] <= '9':
# cast port num from str to int
port = eval(servname)
else:
try:
# Get port num by service name
port = getservbyname(servname, 'tcp')
except error:
sys.stderr.write(servname + ': bad tcp service name\n')
sys.exit(2)
# Create a tcp socket
s = socket(AF_INET, SOCK_STREAM)
# Connect to server
try:
s.connect((host, port))
except error, msg:
sys.stderr.write('connect failed: ' + repr(msg) + '\n')
sys.exit(1)
# Fork a proccess
pid = posix.fork()
#
if pid == 0:
# child -- read stdin, write socket
while 1:
line = sys.stdin.readline()
s.send(line)
else:
# parent -- read socket, write stdout
iac = 0 # Interpret next char as command
opt = '' # Interpret next char as option
while 1:
data = s.recv(BUFSIZE)
# if recv nothing then Exit program
if not data:
# EOF; kill child and exit
sys.stderr.write( '(Closed by remote host)\n')
# Call posix function kill and send signal 9 to child
posix.kill(pid, 9)
sys.exit(1)
cleandata = ''
for c in data:
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(cleandata)
sys.stdout.flush()
try:
main()
except KeyboardInterrupt:
pass
More information about the Python-list
mailing list