class - telnetlib

最後更新: 2016-10-06

介紹

 

 


class

class telnetlib.Telnet([host[, port[, timeout]]])

 

read

 * read_until read_some, read_all, expect 都是會 Block IO 的

 * read_until 讀走的 expected msg, 再 read_some 就會見唔到 expected msg

# Read until a given string, expected, is encountered or until timeout seconds

# 只 return expected msg

Telnet.read_until(expected[, timeout])

# Read at least one byte of cooked data unless EOF is hit.

# Return '' if EOF is hit.

Telnet.read_some()

 * 它真係讀 some, 所以係讀唔晒的.

解決

def printmsg(tn):
    msg = tn.read_until('\n')
    print msg

# Read until one from a list of a regular expressions matches.

# a list of regular expressions, either compiled (regex objects) or uncompiled (strings).

# Return a tuple of three items:

#    the index in the list of the first regular expression that matches;

#    the match object returned;

#    the text read up till and including the match.

Telnet.read_all()

# Read until one from a list of a regular expressions matches.

# Return a tuple of three items:

#   the index in the list of the first regular expression that matches;

#   the match object returned;

#   the text read up till and including the match.

Telnet.expect(list[, timeout])

debug

# Print a debug message when the debug level is > 0.

Telnet.msg(msg[, *args])

# Set the debug level.

Telnet.set_debuglevel(n)

Telnet(r.r.r.r): recv '220 server ESMTP Postfix\r\n'
Telnet(r.r.r.r): send 'helo client\n'
Telnet(r.r.r.r): recv '250 server\r\n'
Telnet(r.r.r.r): send 'mail from: postmaster@client\n'
Telnet(r.r.r.r): recv '250 2.1.0 Ok\r\n'
Telnet(r.r.r.r): send 'rcpt to: datahunter@client\n'
Telnet(r.r.r.r): recv '454 4.7.1 <datahunter@client>: Relay access deni'
454 4.7.1 <datahunter@client>: Relay access deni
Telnet(r.r.r.r): send 'quit\n'

write

# Write a string to the socket, doubling any IAC characters.

Telnet.write(buffer)

# Close the connection.

close

Telnet.close()

 


telnet.py

#!/usr/bin/env python

import telnetlib

server='117.18.98.149'
port='25'

helo_msg='helo hlhk.net'
from_msg='mail from: x@x.x.x'
to_msg='rcpt to: datahunter@datahunter.org'

def connect(server, port):
    tn = telnetlib.Telnet(server, port)
    return tn

def quit(tn):
    tn.write("quit\n")
    tn.close()

def printmsg(tn):
    #msg = tn.read_some()         # read_some 真係 read 小小, 句 msg 出唔晒
    msg = tn.read_until('\n')
    print msg

tn = connect(server, port)
tn.read_until('220 ', 3)
tn.write( helo_msg + '\n' )
tn.read_until('250 ', 3)
tn.write( from_msg + '\n' )
tn.read_until('250 ', 3)
tn.write( to_msg + '\n' )
printmsg(tn)

tn.write("data" + '\n')
printmsg(tn)
tn.write( "test msg" + '\r\n' + '.' + '\r\n')
printmsg(tn)

quit(tn)