Wednesday, July 29, 2009

Iterating over a sequence of IPs in Python

I was bit bored, so I wrote a simple iterator that iterates over a sequence of IPs using a subnet bitmask.

import struct
import socket

class IPIterator:
def __init__(self, ip, bitmask):
self.ip = ip
self.bitmask = bitmask
def __iter__(self):
ipnum = struct.unpack(">L", socket.inet_aton(self.ip))[0]
mask = 2 ** self.bitmask - 1
for x in xrange(ipnum & ~mask, ipnum | mask):
yield socket.inet_ntoa(struct.pack(">L", x))

if __name__ == "__main__":
for x in IPIterator("1.2.3.4", 8):
print x

Friday, February 6, 2009

Playing with signals in Python

A Python program is able to catch signals and handle them with the signal module. This is especially useful when you want to clean up after your program exits for any reason. This can be done with signal.signal, which sets a callback function for signal handlers.

This code will set an "alarm" that must be set every 30 seconds, or else a signal will be called to shut down the program (sort of a "watchdog" program).


def alarm_handler(signum, frame):
print "30 seconds have passed!"

signal.signal(signal.SIGALRM, alarm_handler)

signal.alarm(30)

while True:
data = raw_input("Write something in the next 30 seconds please: ")
signal.alarm(30)


Another use of signals would be to brutally terminate your program, since sometimes Python can hang on I/O, or a Thread object that is running (for some reason a Ctrl+C doesn't kill a program running a python thread):


import os, signal

# Brutally terminate this process
os.kill(0, signal.SIGTERM)

Sending E-Mail using Python

Well, it's really easy, all you need to do is build up a MIME message using the Python "email" library.

I am using the "alternative" multipart content type, which allows be to enter both text content and HTML content, and display the supported content type (which will of course almost always be HTML, but there are a lot of guys who still use text clients to read emails apparently).

I also used a small line in the example that convert from simple text to HTML.

Here is a sample code:


#!/usr/bin/python
import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

# We are using the local SMTP server
MAIL_SERVER = "localhost"

class Mailer:
def __init__(self):
self.mail_server = MAIL_SERVER

def send_raw_email(self, mail_from, mail_to, data):
smtp = smtplib.SMTP(self.mail_server)
smtp.sendmail(mail_from, mail_to, data)
smtp.quit()

def send_email(self, mail_from, mail_to, subject, text_message, html_message='', images=[]):
# Initialize MIME message
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = mail_from
if type(mail_to) is str:
msg["To"] = mail_to
else:
msg["To"] = ", ".join(mail_to)

text = MIMEText(text_message)
msg.attach(text)

if html_message:
html = MIMEText(html_message, "html")
msg.attach(html)

for image in images:
image = MIMEImage(open(image, "rb"))
msg.attach(image)

self.send_raw_email(mail_from, mail_to, msg.as_string())

if __name__ == '__main__':
mailer = Mailer()

subject = "This is the subject"
message = "This is the message"

html = "<html dir="'ltr'"><body>%s</body></html>" % message.replace("\n", "<br/>")
mailer.send_email("admin@myserver.com", "recipient@example.com", subject, message, html)

Thursday, February 5, 2009

Really cheap webhosting?

If you ever wanted to have unlimited websites managed all from one place, instead of paying for extremely limited access to hosting servers which are insecure, and expensive?

I got myself my first VPS a few days ago from http://www.vpsvillage.com. It costs me only 6$/mo and I get to put there as many websites I want (well, it's my server, that's the point of it). Not only that, but a VPS is much more secure than shared webhosting. If a hacker takes over a shared hosting server from any webpage, he could easily take over your files and read your source code from the websites (which could often contain passwords and other secret information). It's not that it's impossible to take over a VPS hosting server, it's just much more difficult to do even if a hacker succeeds on taking over one of the VPS servers.

Of course there's a catch - you have to learn how to be your own webhosting IT manager. I admit - it's not an easy task, but once you learn how to do it, having full control over your website is a huge benefit.

I would suggest using Debian for a start, and reading some HOWTO's on howtoforge.com. For example, to set up a LAMP server (Linux/Apache/MySQL/PHP), what you should do is follow simple instructions from here - http://www.howtoforge.com/ubuntu_debian_lamp_server. Setting up unlimited (duuuh) mailboxes and mail forwarding is easily done using postfix, and you can even set up your own DNS server on the VPS, so adding domains to your VPS is also very easy.

Tuesday, January 6, 2009

Writing webbots using Python

If you ever wanted to write a webbot and didn't know how, it could be easily achieved using the mechanize module.

There is one thing that mechanize does which doesn't always suit my needs, which is to pay attention to the robots.txt file, so I just disable it.

Mechanize allows you to easily browse, extract data and submit forms.

import mechanize

br = mechanize.Browser()
br.set_handle_robots(False)
br.open("http://www.google.com")

for link in br.links():
print link

Using Python and MySQL

I use the MySQLPython module, which is very easy to use.
To return results as a dictionary or as a tuple, we use the DictCursor to fetch rows.

import MySQLdb
import MySQLdb.cursors

conn = MySQLdb.connect(
host = "localhost",
user = "xxx",
passwd = "xxx",
db = "xxx",
cursorclass = MySQLdb.cursors.DictCursor)

cur = conn.cursor()

cur.execute("select id, address from phonebook where city_id = 0")

data = cur.fetchall()