Archive

Archive for the ‘python’ Category

Make good use of string formatting with python

April 8, 2010 Leave a comment

Sometimes it’s better to separate program from content (MVC web programming is a good example). With python’s string formatting feature, this can be done quite easily. I am going to borrow a party emailing example from “Unix Shells by Example” and simplify it a bit. Let’s say I am going to hold a party and I am going to email my friends asking each of them to bring something for the party. I start by writing the following python script (main.py) and the email template (content)

main.py:

#!/usr/bin/env python
        
def main():
        friends=[
                { 'name':'Leah', 'stuff':'some cookies' },
                { 'name':'Michael', 'stuff':'a lot of beers' },
                { 'name':'Rachael', 'stuff':'a red wine' }
        ]
                
        with open('content') as f:
                content=f.read()

        for friend in friends:
                print(content % friend)
        

if __name__=='__main__':
        main()

content:

Dear %(name)s,
We are going to have a party this Friday night at my place, please make sure to bring %(stuff)s.

Sincerely Yours,
Party Animal

Save both files and at command prompt, run

python main.py

Password generating with python

July 29, 2009 Leave a comment

Direct Link
http://rc3.fileave.com/mkpass.py.txt

View Code (in colors)

To see the script in action, please visit my first Google App: http://genpswd.appspot.com/

Example Usage:

Categories: Programming, python

myping.py

June 28, 2009 Leave a comment

A ping script using python thread. Examples of usage:

myping.py -n 192.168.1 -s 10 -e 150
  Scans 192.168.1.10 – 192.168.1.150
myping.py -n 172.16.0 -g
  Scans 172.16.0.0/24 subnet and returns active hosts only

[ direct link: http://rc3.fileave.com/myping.py.txt ]

#!/usr/bin/env python
DEBUG=False
import os
import re
import time
from threading import Thread

class pingtest(Thread):
	def __init__ (self,ip):
		Thread.__init__(self)
		self.ip = ip
		# -1 means not found, any other number indicates 
		#the index of the found pattern
		self.status = -1 
	def run(self):
		pingaling = os.popen("ping -q -c 2 -w 3 "+self.ip,"r")
		while 1:
			line = pingaling.readline()
			if not line: break
			igot = re.findall(pingtest.lifeline,line)
			if igot:
				self.status = int(igot[0])

def usage():
	print('''\
	usage 1:
	myping.py -n network_adr [ -s start -e end -g ]
	for example: myping -n 192.168.1 -s 10 -e 150

	usage 2:
	myping.py -f ip_list_file [ -g ]
	''')
if __name__=="__main__":
	import sys
	if (len(sys.argv)) < 2:
		usage()
		sys.exit()
	else:
		import getopt
		try:
			opts, args = getopt.getopt( sys.argv[1:], 'n:s:e:f:hg' )
		except getopt.GetoptError, err:
			usage()
			print str(err)
			sys.exit(1)

		#variables initialize:
		S=1
		E=254
		N=''
		FILE=''
		GOODONLY=False
		for o, a in opts:
			if DEBUG: print o
			if o == '-h':
				usage()
				sys.exit(0)
			elif o=='-g':
				GOODONLY=True
			elif o=='-n':
				N=a
			elif o=='-s':
				try:
					S=int(a)
				except Exception:
					print("int argument expected")
			elif o=='-e':
				try:
					E=int(a)
				except Exception:
					print("int argument expected")
			elif o=='-f':
				FILE=a
			else:
				assert False, "unhandled option"

		if len(N) > 0 and len(FILE)>0:
			usage()
			print("Please do not specify -n and -f at the same time")
			sys.exit(1)
		elif len(N)==0 and len(FILE)==0:
			usage()
			print("Please specify option -n or -f")
			sys.exit(1)
		else:
			pinglist = []
			pingtest.lifeline = re.compile(r"(\d) received")
			report = ("No response","Partial Response","Alive")
			print "***ping started: " + time.ctime()
			if len(N)>0:
				for host in range(S,E):
					ip = N + '.'+ str(host)
					current = pingtest(ip)
					pinglist.append(current)
					current.start()
			elif len(FILE)>0:
				try:
					f=open(FILE)
					for ip in f:
						current=pingtest(ip.strip())
						pinglist.append(current)
						current.start()
					f.close()
				except IOError, err:
					print( str(err) )
			for pingle in pinglist:
				pingle.join()
				if GOODONLY:
					if pingle.status == 2: 
						print "Status from ",pingle.ip,\
							 ": ",report[pingle.status]
				else:
					print "Status from ",pingle.ip,": ",report[pingle.status]
			print "***ping finished: "+time.ctime()

 

If you have fping installed, you can achieve the similar results with the following perl one-liner

perl -e 'for (1..254) { print "192.168.1.$_\n" }' | fping -a -q 2>/dev/null

Categories: Networking, Programming, python