class - telnetlib

最後更新: 2016-10-06

介紹

 

 


class

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

read_X

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

read_until(STRING)

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

 * 只 return expected msg

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

Telnet.read_until(expected[, timeout])

read_all

Read all data until EOF; block until connection closed.

expect

# 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)


write

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

Telnet.write(buffer)

close

# Close the connection.

Telnet.close()

 


Example

 

SMTP

#!/usr/bin/env python

import telnetlib

server='R.R.R.R'
port='25'

helo_msg='helo datahunter.org'
from_msg='mail from: [email protected]'
to_msg='rcpt to: [email protected]'

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

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

def printmsg(tn):
    # read_some 真係 read 小小, msg 出唔晒,
    # 所以要用 read_until
    #msg = tn.read_some()
    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)

 

HTTP Post Data

myTelHTTP.py

#!/usr/bin/env python
# vim: sts=4:ts=4:sw=4:paste:et
import telnetlib
import os

server='datahunter.org'
port='80'

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

def wmsg(tn, msg):
    tn.write(msg + '\r\n')

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

def printall(tn):
    msg = tn.read_all()
    print msg

if __name__ == '__main__':
    tn = connect(server, port)
    wmsg(tn, 'POST /test.php HTTP/1.1')
    wmsg(tn, 'Host: ' + server)
    wmsg(tn, 'Content-Type: text/plain')
    wmsg(tn, 'Content-Length: 4')
    wmsg(tn, '')
    wmsg(tn, 'test')

    printheader(tn)
    printall(tn)

 

 

Creative Commons license icon Creative Commons license icon