18. Internet Services

Simple DNS Lookups


import socket
try:
    host_info = socket.gethostbyname_ex(name)
    # (hostname, aliaslist, ipaddrlist)
except socket.gaierror, err:
    print "Can't resolve hostname %s: %s" % (name, err[1])
                    
# if you only need the first one
import socket
try:
    address = socket.gethostbyname(name)
except socket.gaierror, err:
    print "Can't resolve hostname %s: %s" % (name, err[1])

# if you have an ip address
try:
    host_info = socket.gethostbyaddr(address)
    # (hostname, aliaslist, ipaddrlist)
except socket.gaierror, err:
    print "Can't resolve address %s: %s" % (address, err[1])
                    
# checking back
import socket
try:
    host_info = socket.gethostbyaddr(address)
except socket.gaierror, err:
    print "Can't look up %s: %s" % (address, err[1])
    raise SystemExit(1)
try:
    host_info = socket.gethostbyname_ex(name)
except:
    print "Can't look up %s: %s" % (name, err[1])
    raise SystemExit(1)

found = address in host_info[2]

# use dnspython for more complex jobs.
# download the following standalone program
#!/usr/bin/python
# mxhost - find mx exchangers for a host

import sys

import dns
import dns.resolver

answers = dns.resolver.query(sys.argv[1], 'MX')
for rdata in answers:
    print rdata.preference, rdata.exchange



# download the following standalone program
#!/usr/bin/python
# hostaddrs - canonize name and show addresses

import sys
import socket
name = sys.argv[1]
hent = socket.gethostbyname_ex(name)
print "%s aliases: %s => %s" % (
            hent[0],
            len(hent[1])==0 and "None" or ",".join(hent[1]),
            ",".join(hent[2]) )

Being an FTP Client

import ftplib
ftp = ftplib.FTP("ftp.host.com")
ftp.login(username, password)
ftp.cwd(directory)

# get file
outfile = open(filename, "wb")
ftp.retrbinary("RETR %s" % filename, outfile.write)
outfile.close()

# upload file
upfile = open(upfilename, "rb")
ftp.storbinary("STOR %s" % upfilename, upfile)
upfile.close()

ftp.quit()

Sending Mail

import smtplib
from email.MIMEText import MIMEText

msg = MIMEText(body)
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = subject

mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_address, [to_address], msg.as_string())

Reading and Posting Usenet News Messages

import nntplib

# You can except nntplib.NNTPError to process errors
# instead of displaying traceback.

server = nntplib.NNTP("news.example.com")
response, count, first, last, name = server.group("misc.test")
headers = server.head(first)
bodytext = server.body(first)
article = server.article(first)

f = file("article.txt")
server.post(f)

response, grouplist = server.list()
for group in grouplist:
    name, last, first, flag = group
    if flag == 'y':
        pass  # I can post to group

Reading Mail with POP3

import poplib

pop = poplib.POP3("mail.example.com")
pop.user(username)
pop.pass_(password)
count, size = pop.stat()
for i in range(1, count+1):
    reponse, message, octets = pop.retr(i)
    # message is a list of lines
    pop.dele(i)

# You must quit, otherwise mailbox remains locked.
pop.quit()

Simulating Telnet from a Program


import telnetlib

tn = telnetlib.Telnet(hostname)

tn.read_until("login: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
# read the logon message up to the prompt
d = tn.expect([prompt,], 10)
tn.write("ls\n")
files = d[2].split()
print len(files), "files"
tn.write("exit\n")
print tn.read_all() # blocks till eof

Pinging a Machine

# @@INCOMPLETE@@
# @@INCOMPLETE@@

Using Whois to Retrieve Information from the InterNIC

# @@INCOMPLETE@@
# @@INCOMPLETE@@

Program: expn and vrfy

# @@INCOMPLETE@@
# @@INCOMPLETE@@