2010-09-08 07:28:20

Calculating network subnetting with Python

I created this program last year just as an exercise to make sure that I understood the mathmatical processes behind IP subnetting, and could create a network calculator based off that information.

The code below isn't meant to be pretty ... If I spent a little time on it, I could modularize, simplify, and comment the heck out of it, but this code is a byproduct of the network subnetting task that I set for myself, not the end result.

The program will randomly generate an IP and subnet, then generate a quiz for the following questions:

  • Class
  • Increment
  • Netmask
  • IP Address in binary
  • Netmask in binary
  • Network IP
  • Broadcast IP
  • Number of subnets
  • Number of hosts
#!/bin/env python
#################################################################
# Who: James Conner
# When: Feb 24, 2009
# What: pysub
# Version: 0.0.1
# Why: Test subnetting for Cisco exams
#################################################################
# Updates:
# 0.0.1:James Conner:Feb 24, 2009
#   Initial creation
# 0.0.2:James Conner:Feb 27, 2009
#   Added network and broadcast IPs
#################################################################
# Notes:
# Need error and exception controls
#################################################################

#################################################################
# Modules
#################################################################
import optparse
import sys, os
import string
import random
import datetime


#################################################################
# Global Variables
#################################################################
stamp = datetime.datetime.now()


#################################################################
# Classes
#################################################################


#################################################################
# Functions
#################################################################
def int2bin(n, count=8):
  return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])

def gen_IP():
  oct1=random.randrange(0,223)
  oct2=random.randrange(0,255)
  oct3=random.randrange(0,255)
  oct4=random.randrange(0,255)
  while oct1 == 127:
    oct1=random.randrange(0,223)
  ipaddr=str(oct1)+"."+str(oct2)+"."+str(oct3)+"."+str(oct4)
  ipaddr_list=[oct1,oct2,oct3,oct4]
  ipaddr_list_binary=[int2bin(ipaddr_list[0]), int2bin(ipaddr_list[1]), int2bin(ipaddr_list[2]), int2bin(ipaddr_list[3])]
  ipaddr_binary=ipaddr_list_binary[0]+"." +ipaddr_list_binary[1]+"." +ipaddr_list_binary[2]+"." +ipaddr_list_binary[3]

  if oct1 <= 126:
    netclass="A"
  elif oct1 <= 191:
    netclass="B"
  elif oct1 <= 223:
    netclass="C"
  else:
    print("Determining netclass failed")

  randmask=str(256-(2**random.randrange(0,8)))

  if netclass == "C":
    while randmask=="255":
      randmask=str(256-(2**random.randrange(0,8)))
    netmask_temp=[255,255,255,randmask]
  elif netclass == "B":
    a=random.randrange(0,1)
    if a == 0:
      while randmask=="255":
        randmask=str(256-(2**random.randrange(0,8)))
      netmask_temp=[255,255,255,randmask]
    elif a == 1:
      netmask_temp=[255,255,randmask,0]
    else:
      print("netclass_temp B is out of bounds")
  elif netclass == "A":
    a=random.randrange(0,2)
    if a == 0:
      while randmask=="255":
        randmask=str(256-(2**random.randrange(0,8)))
      netmask_temp=[255,255,255,randmask]
    elif a == 1:
      netmask_temp=[255,255,randmask,0]
    elif a == 2:
      netmask_temp=[255,randmask,0,0]
    else:
      print("netclass_temp A is out of bounds")
  else:
    print("No netclass corresponding")
  netmask_list=[netmask_temp[0],netmask_temp[1],netmask_temp[2],netmask_temp[3]]
  netmask=str(netmask_list[0])+"." +str(netmask_list[1])+"." +str(netmask_list[2])+"."+ str(netmask_list[3])
  netmask_list_binary=[int2bin(int(netmask_list[0])), int2bin(int(netmask_list[1])), int2bin(int(netmask_list[2])), int2bin(int(netmask_list[3]))]
  netmask_binary=str(netmask_list_binary[0])+"." +str(netmask_list_binary[1])+"." +str(netmask_list_binary[2])+"." +str(netmask_list_binary[3])
  increment=256-int(randmask)
  netip_list=[int(ipaddr_list[0])& int(netmask_list[0]),int(ipaddr_list[1])& int(netmask_list[1]),int(ipaddr_list[2])& int(netmask_list[2]),int(ipaddr_list[3])& int(netmask_list[3])]
  broadcastip_mask_list=[((int(ipaddr_list[0])| int(netmask_list[0]))-255)*-1,((int(ipaddr_list[1])| int(netmask_list[1]))-255)*-1,((int(ipaddr_list[2])| int(netmask_list[2]))-255)*-1,((int(ipaddr_list[3])| int(netmask_list[3]))-255)*-1]
  broadcastip_list=[int(ipaddr_list[0])+ int(broadcastip_mask_list[0]), int(ipaddr_list[1])+ int(broadcastip_mask_list[1]), int(ipaddr_list[2])+ int(broadcastip_mask_list[2]), int(ipaddr_list[3])+ int(broadcastip_mask_list[3])]


  broadcastip=str(broadcastip_list[0])+"."+ str(broadcastip_list[1])+"." +str(broadcastip_list[2])+"." +str(broadcastip_list[3])
  netip=str(netip_list[0])+"." +str(netip_list[1])+"." +str(netip_list[2])+"." +str(netip_list[3])


  if netclass == "A":
    subnets=(2**(str(netmask_binary).count("1")-8))
  elif netclass == "B":
    subnets=(2**(str(netmask_binary).count("1")-16))
  elif netclass == "C":
    subnets=(2**(str(netmask_binary).count("1")-24))
  else:
    print("subnets is messed up")

  hosts=(2**(str(netmask_binary).count("0"))-2)

  print("-"*64)
  print("IP: "+str(ipaddr)+"/"+str(str(netmask_binary).count("1")))
  print("-"*64)

  answer_class = raw_input("Class: ")
  if answer_class == netclass:
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(netclass))

  answer_increment = raw_input("Increment: ")
  if str(answer_increment) == str(increment):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(increment))

  answer_netmask = raw_input("Mask: ")
  if str(answer_netmask) == str(netmask):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(netmask))

  answer_ipaddr_binary = raw_input("IP Binary: ")
  if str(answer_ipaddr_binary) == str(ipaddr_binary):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(ipaddr_binary))

  answer_netmask_binary = raw_input("Mask Binary: ")
  if str(answer_netmask_binary) == str(netmask_binary):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(netmask_binary))

  answer_netip = raw_input("Network IP: ")
  if str(answer_netip) == str(netip):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(netip))

  answer_broadcastip = raw_input("Broadcast IP: ")
  if str(answer_broadcastip) == str(broadcastip):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(broadcastip))

  answer_subnets = raw_input("Subnets: ")
  if str(answer_subnets) == str(subnets):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(subnets))

  answer_hosts = raw_input("Hosts: ")
  if str(answer_hosts) == str(hosts):
    print ("Correct!")
  else:
    print ("Wrong! The answer is: "+str(hosts))



#################################################################
# Option Parser
#################################################################
parser = optparse.OptionParser(version = "0.0.2")
parser.set_defaults(mode="advanced")
(opts, arg) = parser.parse_args()


#################################################################
# Program Execution
#################################################################
if __name__ == '__main__':
    gen_IP()

Tags:   python     |    Perm Link:   Calculating network subnetting with Python



2009-02-14 02:13:25

Func and CertMaster

One of the major complications with dealing with large server farms is the easy distributing and executing of arbitrary commands.

The most common solution for this issue is SSH key pair exchanges. I've built a few solutions using that design, and it works quite well ... to a point. Things like key revocation, meta-character handling, error and exception handling, and so forth are a bit of a pain to deal with in that sort of solution. Scale it up to a few hundred servers, and now you have a problem manging the whole thing. Working within a structured language like Python, using the Paramiko SSH module, you can largely mitigate most of those issues, but it's not perfect. Your keypair administration is still overly complicated. Enter Func and CertMaster.

CertMaster is an SSL certificate server ... long story short, it handles the authentication piece that replaces the SSH keypairs. Func (Fedora Unified Network Controller) is a program which grabs the server SSL cert from the CertMaster server, and allows you to run arbitrary commands through SSL encrypted channels. Overall, that doesn't get you much more than the old way of using the SSH keypairs ... but there's a twist.

Func includes a Python API, simplifying the entire process of executing arbitrary commands, and also enables the ability to easily add modules for frequently used processes, or very large processes. Couple that into the ability to execute asynchronously, and you've got an interesting solution. Fun stuff.

Tags:   python     |    Perm Link:   Func and CertMaster



2009-01-17 17:46:15

Using Python to decode SAS passwords

One of the SAS recommended methods for dealing with scripted processes is to use a clear text password in SAS 9.1. Please don't do that.

The other method promotes security by using an encoded password. Unfortunately, the password can be easily reversed because it uses a trivial encoding mechanism.

Here is an example, using SAS, to generate an encoded password for usage in SAS scripts:

proc PWENCODE in="flummoxedpygmy";
run;
{sas001}Zmx1bW1veGVkcHlnbXk=

And now, to decode it using Python:

[root@navi ~]# python
Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:56)
[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import base64
>>> coded_pwd = "Zmx1bW1veGVkcHlnbXk="
>>> decoded_pwd = base64.b64decode(coded_pwd)
>>> print(decoded_pwd)
flummoxedpygmy

As it stands, the method that SAS uses for password encoding leaves the SAS accounts vulnerable to being hacked by reversing that encoding, if the script files can be read by users. One way hashes, with salts, would have provided better security, and would be easy to implement.

Tags:   python     |    Perm Link:   Using Python to decode SAS passwords



2008-08-21 23:15:13

Hash fields in a CSV file with Python and SHA256

I had a request recently where someone asked for a quick and dirty script that would take a CSV file, and parse certain fields for hashing. I decided to use python due to the nice speed of the hashlib module (and because I simply like python!).

If you look at the code, it doesn't contain two things ... comments and error checking. I know, I know. That's coming in the next version. Remember, I was asked for "quick and dirty"!

One thing to note is that the script can handle multiple field arguments. So, for example, you can use the following argument: "-f 2 -f 3 -f 8" and it will parse the 3rd, 4th and 9th field (counting begins at zero :)

The other thing to notice is that there is a --md5 option. I was asked to add that feature since the SHA256 output is extremely long and takes up a lot of space in a database when you're talking a few billion rows. The --md5 option takes the SHA256 output and performs an MD5 hash on it, reducing it to a smaller, but still unique, string.

#!/bin/env python
#################################################################
# Who: James Conner
# When: June 16, 2008
# What: csv_hash.py
# Version: 1.0.1
# Why: Encrypt fields within a CSV file
#################################################################
# Updates:
# Ver:Who:When:Why
# 0.0.1:James Conner:Jun 16 2008:Initial creation
# 0.0.2:James Conner:Jul 07 2008:Added multi field hashing
# 1.0.0:James Conner:Aug 21 2008:Added MD5 output of SHA256 hash
# 1.0.1:James Conner:Aug 21 2008:Fixed field check
#################################################################

#################################################################
# Import Modules
#################################################################
import os
import sys
import string
import hashlib
import csv
from optparse import OptionParser

#################################################################
# Global Variables
#################################################################

#################################################################
# Option Parser
#################################################################
parser = OptionParser(version = "1.0.1")

parser.add_option('-d','--delimiter',
        dest='delimiter_info',
        default=',',
        metavar='DELIMIT',
        help=('The delimiter. Default is \',\'.'))

parser.add_option('-i','--infile',
        dest='infilename_info',
        default='',
        metavar='INFILENAME',
        help=('Name of the input file'))

parser.add_option('-f','--field',
        dest='field_info',
        action='append',
        type='int',
        metavar='FIELDNUM',
        #default='0', # int does not allow a default value
        help=('Which field to encrypt, default is 0'))

parser.add_option('-o','--outfile',
        dest='outfilename_info',
        default='outfile.csv',
        metavar='OUTFILENAME',
        help=('Name of the output file'))

parser.add_option('--md5',
        dest='md5_info',
        action='store_true',
        default=False,
        metavar='MD5',
        help=('Use MD5 against the SHA256 hash.'))

(opts, arg) = parser.parse_args()

#################################################################
# Functions
#################################################################

def check_options(option,option_name):
        if not option:
                print "ERROR: %s variable has not been assigned!" % option_name
                sys.exit(10)

def perf_hash (DATA,MD5):
        if MD5 is True:
                TEMP_DATA = hashlib.sha256(DATA).hexdigest().strip()
                return (hashlib.md5(TEMP_DATA).hexdigest())
        else:
                return(hashlib.sha256(DATA).hexdigest())

def csv_file (FILENAME,DELIMITER,FIELDNUM,OUTFILE,MD5FLAG):
        r = csv.reader(open(FILENAME, 'r'), dialect='excel', delimiter=DELIMITER)
        w = csv.writer(open(OUTFILE, 'w'), dialect='excel', delimiter=DELIMITER)
        for rows in r:
                for f in FIELDNUM:
                        rows[int(f)] = perf_hash(rows[int(f)],MD5FLAG)
                w.writerow(rows)
        sys.exit(0)

#################################################################
# Program Execution
#################################################################

check_options(opts.infilename_info, "infilename_info") check_options(opts.field_info, "field_info")

csv_file(opts.infilename_info, opts.delimiter_info, opts.field_info, opts.outfilename_info, opts.md5_info)

Tags:   python     |    Perm Link:   Hash fields in a CSV file with Python and SHA256



2008-04-05 23:27:56

Downtime communications database ...

Yet another little "somethin' somethin'" I've been putting together in my spare time is a downtimes communications database and web portal for declaring downtimes based on servers, clusters, regions, processes, etc. I know there's quite a few products out there already that can do this, but ... 'eh, this is what I do for fun.

The premise is pretty simple ... my company is all about data. It's a market research company, so if you don't have the data, you don't have a product to sell, in a nutshell. This means that any sort of downtimes impacting the availability of data access has to be minimized as much as possible.

The problem, of course, is the complex issue of data ownership. Who is responsible for what data, and needs to be informed of downtimes. By utilizing a communications manager, you can centralize the communications and focus them away from the engineers performing the work. A comms manager, however, doesn't necessarily have the information regarding data ownership for the impacted services. This situation is further exacerbated by phenomenal growth, introducing new data owners at a very high rate.

In this scenario, you need a normalized database with a high grade of referential integrity, linking servers, services, downtime coordinators, communication managers, clusters, regions, and so forth, together into an easy to manipulate fabric.


For this particular project, I chose fairly standard tools ... Python, MySQL and Apache. The Apache/Python interface allows you to select the type of downtime reports that you want to generate. At the moment, it prints out a simple HTML page with all of the requisite data owner and coordinator information, however, the next iteration of the project will include PDF files. The goal is to produce an output which can be attached to Change Management documentation, and included as part of the official change process.

I love this stuff!

Tags:   web, python     |    Perm Link:   Downtime communications database ...



2008-02-17 11:37:58

Python snmp example using pysnmp

Here's a simple python program that makes an snmp query against network interface descriptions, and then grabs the physical address of that interface using another snmp call.

#!/usr/bin/env python
import re, os, sys, getopt, string, commands
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.entity.rfc3413 import mibvar
from pysnmp.proto import rfc1902

SNMP_HOST='127.0.0.1'
SNMP_RO_STRING='whatever'
SNMP_PORT=161

IOD_sysdescr=[1,3,6,1,2,1,1,1,0]
IOD_descr=[1,3,6,1,2,1,2,2,1,2]
IOD_phyaddr=[1,3,6,1,2,1,2,2,1,6]
IOD_type=[1,3,6,1,2,1,2,2,1,3]
IOD_speed=[1,3,6,1,2,1,2,2,1,5]
IOD_alias=[1,3,6,1,2,1,31,1,1,1,18]
    
def main():
    cmdGen = cmdgen.CommandGenerator()
    errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
        cmdgen.CommunityData('duofold', SNMP_RO_STRING), cmdgen.UdpTransportTarget((SNMP_HOST, SNMP_PORT)),
        (('IF-MIB', 'ifDescr'),),)

    if errorIndication:
        print errorIndication
    else:
        if errorStatus:
            print '%s at %s\n' % (errorStatus.prettyPrint(),varBindTable[-1][int(errorIndex)-1])
        else:
            for varBindTableRow in varBindTable:
                for oid, val in varBindTableRow:
                    (symName, modName), indices = mibvar.oidToMibName(cmdGen.mibViewController, oid)
                    val = mibvar.cloneFromMibValue(cmdGen.mibViewController, modName, symName, val)
                    #print '%s::%s.%s = %s' % (modName, symName,string.join(map(lambda v: v.prettyPrint(), indices), '.'),val.prettyPrint())
                    INTERFACE=oid.prettyPrint().split('.')[-1:].pop(0)
                    get_attr(INTERFACE,IOD_phyaddr)


def get_attr(interface,attr):
    cmdGen = cmdgen.CommandGenerator()
    IOD_list=attr+[int(interface)]
    IOD=tuple(IOD_list)
    errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd(
        cmdgen.CommunityData('edson', SNMP_RO_STRING),cmdgen.UdpTransportTarget((SNMP_HOST, SNMP_PORT)),(IOD))
    if errorIndication:
        print errorIndication
    else:
        if errorStatus:
            print '%s at %s\n' % (errorStatus.prettyPrint(), varBinds[int(errorIndex)-1])
        else:
            for name, val in varBinds:
                if attr==IOD_phyaddr:
                    print '%s = %s' % (name.prettyPrint(), hexify(val))
                else:
                    print '%s = %s' % (name.prettyPrint(), val.prettyPrint())

def hexify(input):
    return ":".join([ '%x'%(ord(s)) for s in input])

main()

Tags:   python     |    Perm Link:   Python snmp example using pysnmp



2007-10-01 19:31:18

Check if FTP server is running

#!/usr/bin/env python
#################################################################
# Who: James Conner
# When: October 1, 2007
# What: FTP service checker
# Version: 0.0.1
# Why: Check if an FTP server is up
#################################################################
# Updates:
# Ver:Who:When:Why
# 0.0.1:James Conner:Oct 01 2007:Initial creation
#################################################################
import os
import sys
import smtplib
import socket
from optparse import OptionParser
from ftplib import FTP

#################################################################
# Global Variables
#################################################################
run_user="bob"
notify_user=["person1@email.com","person2@email.com"]
mailsvr="smtp.your.domain.com"
hostname=socket.gethostname()

#################################################################
# Option Parser
#################################################################
parser = OptionParser(version = "0.0.1")

parser.add_option('-s','--server',
  dest='server_info',
  default='',
  metavar='SVRNAME',
  help=('Server to check'))

parser.add_option('-u','--user',
  dest='user_info',
  default='anonymous',
  metavar='USRNAME',
  help=('Username to log into the server. Default is \'anonymous\'.'))

parser.add_option('-p','--password','--pass',
  dest='pass_info',
  default='person1@email.com',
  metavar='PASSWRD',
  help=('Password to log into the server. Default is \'person1@email.com\'.'))

(opts, arg) = parser.parse_args()

#################################################################
# Functions
#################################################################
def check_options(option,option_name):
  if not option:
    print "ERROR: %s variable has not been assigned!" % option_name
    sys.exit(10)

#################################################################
# Program Execution
#################################################################
check_options(opts.server_info, "server_info")

try:
  ftp = FTP(opts.server_info,opts.user_info,opts.pass_info)
  ftp.quit()
except:
  msg="Subject: FTP on %s is down!" % opts.server_info
  server=smtplib.SMTP(mailsvr,25)
  server.sendmail(run_user+"@"+hostname,notify_user,msg)
  server.quit()
  sys.exit(99)

Tags:   python     |    Perm Link:   Check if FTP server is running



2007-09-06 16:57:03

Create hard links in Python

#!/usr/bin/env python
#################################################################
# Who: James Conner
# When: Sep 05, 2007
# What: hard_link_sync
# Version: 0.0.2
# Why: Hard links are needed for contractors to access deep
#      hierarchy files.
#################################################################
# Updates:
# Ver:Who:When:Why
# 0.0.1:James Conner:Sep 05 2007:Initial creation
# 0.0.2:James Conner:Sep 06 2007:Check using os.samefile
#################################################################
import os,sys
from optparse import OptionParser

#################################################################
# Global Variables
#################################################################
#----------------------------------------------------------------
# The CONTRACTOR_DIR gets created under the mount point.  This is
# where all hard links will be created.
#----------------------------------------------------------------
CONTRACTOR_DIR="/contractor"
sys.path.append('/usr/local/bin')

#################################################################
# Option Parser
#################################################################
parser = OptionParser(version = "0.0.2")

parser.add_option('-d','--directory',
  dest='dir_info',
  default='',
  metavar='DIRNAME',
  help=('Perform the action on a directory and its recursive path'))

parser.add_option('-o','--output',
  dest='stdout_info',
  default='',
  metavar='FILENAME',
  help=('Output to a file instead of stdout'))
(opts, arg) = parser.parse_args()

#################################################################
# Functions
#################################################################
#----------------------------------------------------------------
# The find_mount function takes a path as a parameter.  It looks
# at the path to find the highest mount point by splitting the
# path by the "/" character into a list, and then performing the
# "ismount" function from os.path.  Each iteration of the while
# loop looks at 1 fewer items in the path list.  If the counter
# reaches 0, that means the filesystem is "/" and thus sets the
# path to "/".
#----------------------------------------------------------------
def find_mount(path):
  while not os.path.ismount(path):
    splitpath=path.split("/")
    count=len(splitpath)-1
    path="/".join(splitpath[0:count])
    if count == 0:
      path = "/"
      break
  return path

#----------------------------------------------------------------
# The hardlink function takes 3 variables to make it happen. The
# absolute path to the file to be linked to, the highest mount
# point of the filesystem, and the filename (not absolute).
#----------------------------------------------------------------
def hardlink(absolute,mounted_fs,filename):
  if os.path.exists(mounted_fs+CONTRACTOR_DIR):
    splitpath_abs=absolute.split("/")
    if mounted_fs != "/":
      splitpath_mnt=mounted_fs.split("/")
    else:
      splitpath_mnt=mounted_fs
    splitpath_file=filename.split("/")
    abs_len=len(splitpath_abs)
    mnt_len=len(splitpath_mnt)
    path_without_mounted="/".join(splitpath_abs[mnt_len:-1])
    file_to_link=mounted_fs+CONTRACTOR_DIR+"/"+path_without_mounted+"/"+splitpath_file[-1]
    path_to_make=mounted_fs+CONTRACTOR_DIR+"/"+path_without_mounted
    if not os.path.exists(path_to_make):
      os.makedirs(path_to_make, 0775)
      print path_to_make, "created!"
    if not os.path.isfile(file_to_link):
      os.link(absolute,file_to_link)
      print file_to_link,"created!"
    else:
      if os.path.samefile(absolute, file_to_link):
        print file_to_link, "already exists!"
      else:
        print "ERROR:",absolute,"is not the same file as",file_to_link+"!"
        os.remove(file_to_link)
        print file_to_link,"has been removed!"
        os.link(absolute,file_to_link)
        print file_to_link, "successfully relinked!"
  else:
    if os.path.isfile(mounted_fs+CONTRACTOR_DIR):
      print mounted_fs+CONTRACTOR_DIR,"is a file, not a directory!"
      sys.exit(12)
    else:
      os.makedirs(mounted_fs+CONTRACTOR_DIR, 0775)
      print mounted_fs+CONTRACTOR_DIR,"created!"
      hardlink(absolute,mounted_fs,filename)

#----------------------------------------------------------------
# The traverse_dir function takes a target directory, and the
# highest mounted path.  It lists the contents of a directory,
# and passes off files to the hardlink function, while other dirs
# are called recursively until all sub-trees are exhausted.
#----------------------------------------------------------------
def traverse_dir(parent_dir,mount_path):
  if os.path.isdir(parent_dir):
    for i in os.listdir(parent_dir):
      listed_target=os.path.abspath(parent_dir)+"/"+i
      if os.path.isfile(listed_target):
        just_the_filename=listed_target.split("/")[-1]
        hardlink(listed_target,mount_path,just_the_filename)
      if os.path.isdir(listed_target):
        traverse_dir(listed_target,mount_path)

#################################################################
# Program Execution
#################################################################
#----------------------------------------------------------------
# Here's where the fun starts.
# if the -o or --output option has been declared, then we
# redirect stdout to a file, taking care to preserve the old
# stdout, just in case we really need it.
#----------------------------------------------------------------
if opts.stdout_info:
  old_stdout = sys.stdout
  out_file = open(opts.stdout_info, 'w')
  sys.stdout = out_file

#----------------------------------------------------------------
# Happy Happy Joy Joy
#----------------------------------------------------------------
if len(sys.argv) < 2:
  print "No arguments supplied."
  print "Please type",sys.argv[0],"-h to see the options for this program."
elif opts.dir_info:
  if os.path.isdir(opts.dir_info):
    mount_path=find_mount(os.path.abspath(opts.dir_info))
    traverse_dir(os.path.abspath(opts.dir_info),mount_path)
  else:
    print "Not a directory!"
    sys.exit(10)
elif arg:
  for i in arg:
    if os.path.isfile(i):
      mount_path=find_mount(os.path.abspath(i))
      hardlink(os.path.abspath(i),mount_path,i)
    else:
      print "Not a file!"
      sys.exit(11)
else:
  sys.exit(99)

Tags:   python, linux     |    Perm Link:   Create hard links in Python



2007-08-30 21:28:49

View target WWIDS by fibre adapter with Python

#!/usr/bin/env python
import os,sys

driverDir="/proc/scsi/qla2xxx"
EVA_WWIDS={"50019DC":"EVA1", "5001A90":"EVA2", "5002A31":"EVA3", "50087CD":"EVA4", "500CA35":"EVA5"}

def ExamineAdapter(adapter):
 print "Adapter: ",adapter
 f = open(adapter,'r')
 for lines in f.xreadlines():
  if "adapter-port" in lines:
   print lines.strip()
  elif "-target-" in lines:
   for EVA in EVA_WWIDS.keys():
    if EVA in lines.upper():
     print EVA_WWIDS.get(EVA),":",lines.strip()
 print ""
 f.close()

def ListDriverDir():
 driverDirContents=os.listdir(driverDir)
 adapter_port = {}
 for port in driverDirContents:
  adapter_port[port]=(os.path.join(driverDir, port))
 return adapter_port.values()

try:
 portResults=ListDriverDir()
except:
 print "Oops, no drivers!"
 sys.exit(1)
else:
 map(ExamineAdapter, portResults)

Tags:   python, linux     |    Perm Link:   View target WWIDS by fibre adapter with Python



2007-08-29 21:20:38

Python and network sockets

One of the advantages to a high-level language such as Python is the ability to write fairly simple abstract code which produces a fairly complex feature set.

Sockets in Python is an excellent example. In approximately 40 lines of code, a simple client/server application can be built.

Server:

#!/usr/bin/env python
from socket import *
HOST='127.0.0.1'
PORT=27900
BUFFERSIZE=1024
ADDR=(HOST, PORT)
MAXCONNECTIONS=5

svrSocket=socket(AF_INET, SOCK_STREAM)
svrSocket.bind(ADDR)
svrSocket.listen(MAXCONNECTIONS)
while 1:
    print "Waiting for a client to connect..."
    cltSocket, client_info = svrSocket.accept()
    print "Client connected:", client_info

    while 1:
        recv_data = cltSocket.recv(BUFFERSIZE)
        if not recv_data: break
        print recv_data
        cltSocket.send(recv_data)
    cltSocket.close()

svrSocket.close()

Client:

#!/usr/bin/env python
from socket import *
HOST='127.0.0.1'
PORT=27900
BUFFERSIZE=1024
ADDR=(HOST,PORT)
MAXCONNECTIONS=5

sockToSvr=socket(AF_INET, SOCK_STREAM)
sockToSvr.connect(ADDR)

while 1:
    send_data = raw_input('>> ')
    if not send_data: break
    sockToSvr.send(send_data)
    talkBack = sockToSvr.recv(BUFFERSIZE)
    if not talkBack: break
    print talkBack

sockToSvr.close()

Now, this example isn't terribly useful, as it just takes raw input from the client, sends it to the server, which sends it back to the client. However, this very simple sort of client/server is quite useful for things like service and hardware monitoring, trend analysis, etc. Combine this sort of simple code with RRDTool and Apache, for example, and you get a massively configurable trend analysis system that is only limited by your imagination. Drop the data into MySQL for later retrieval, use the built in hashing modules to verify script versions, dump RPM versions into a database, use xml instead of databases, and so forth. In other words ... take this simple concept and have fun with it.

Tags:   python     |    Perm Link:   Python and network sockets



2007-08-24 10:47:12

Enabling Apache to exec python code

In the httpd.conf file, add the following line in the "AddHandler" area:

AddHandler cgi-script .py

If your index page is going to be a .py file, be sure to also include an index.py in your DirectoryIndex line, as well.

Tags:   python, web     |    Perm Link:   Enabling Apache to exec python code



2007-08-11 20:47:46

Simple Menu in Python

#!/usr/bin/python

import sys
import os
import string

width = 80
choice_width = 3
seperator_width = 1
process_width = 20
desc_width = width - choice_width - process_width - (seperator_width * 2)
seperator = ''
selection = [1,2,3,4,5,6]
header_format = '%-*s%*s%*s%*s%*s'
line_format = '%-*d%*s%*s%*s%*s'
home_path = os.environ['HOME']

def clear():
    os.system("clear")

def to_int(in_str):
    "Converts a string to an integer"
    out_num = 0
    if in_str[0] == "-":
        multiplier = -1
        in_str = in_str[1:]
    else:
        multiplier = 1
    for x in range(0,len(in_str)):
        out_num = out_num * 10 + ord(in_str[x]) - ord('0')
    return out_num * multiplier

def ask_question():
    clear()
    print
    print "=" * width
    print header_format % (choice_width, 'Num', seperator_width, seperator,process_width, 'Function', seperator_width, seperator, desc_width, 'Description')
    print "-" * width
    print line_format % (choice_width, 1, seperator_width, seperator, process_width, 'Network Restart', seperator_width, seperator, desc_width, 'Restart the network interfaces')
    print line_format % (choice_width, 2, seperator_width, seperator, process_width, 'SMB Restart', seperator_width, seperator, desc_width, 'Restart the Samba service')
    print line_format % (choice_width, 3,seperator_width, seperator, process_width, 'HTTP Restart', seperator_width, seperator, desc_width, 'Restart the HTTPd service')
    print line_format % (choice_width, 4, seperator_width, seperator, process_width, 'LVM Configuration', seperator_width, seperator, desc_width, 'Open the LVM GUI tool')
    print line_format % (choice_width, 5, seperator_width, seperator, process_width, 'MySQL Restart', seperator_width, seperator, desc_width, 'Perform a restart of the MySQLd service')
    print line_format % (choice_width, 6, seperator_width, seperator, process_width, 'Exit', seperator_width, seperator, desc_width, 'Quit Menu')
    print "=" * width
    print
    print "-" * width
    print "Note: Copyright James Conner"
    print "-" * width
    print
    answer = raw_input('Enter the number for your selection: ')
    answer_converted = to_int(answer)

    if answer_converted in selection:
        if answer_converted == 6:
            sys.exit(0)
        elif answer_converted == 5:
            os.system("service mysqld restart")
            ask_question()
        elif answer_converted == 4:
            os.system("/usr/sbin/system-config-lvm")
            ask_question()
        elif answer_converted == 3:
            os.system("service httpd restart")
            ask_question()
        elif answer_converted == 2:
            os.system("service smb restart")
            ask_question()
        elif answer_converted == 1:
            os.system("service network restart")
            ask_question()
    else:
        ask_question()
ask_question()

Tags:   python     |    Perm Link:   Simple Menu in Python



2007-08-02 20:20:36

PYTHON - Hash Test using SHA512

#!/usr/local/bin/python2.5
import sys,os,string,hashlib
C_SEED=000000000
C_MAX=100000000
C_FILE_input = "c_nums_input.txt"
C_FILE_output = "c_nums_output.txt"

def gen_c_nums ():
    C_FILE_MANIP = open(C_FILE_input,'w')
    for number in range(C_SEED,C_MAX):
        num_string=str(number)
        C_FILE_MANIP.write(num_string)
        C_FILE_MANIP.write("\n")
    C_FILE_MANIP.close()

def hash_c_nums ():
    C_FILE_read = open(C_FILE_input,'r')
    C_FILE_write = open(C_FILE_output,'w')
    for lines in C_FILE_read:
        C_FILE_write.write(string.upper(hashlib.sha512(lines.strip()).hexdigest()))
        C_FILE_write.write("\n")
    C_FILE_read.close()
    C_FILE_write.close()

gen_c_nums()
hash_c_nums()

sys.exit(0)

Tags:   python     |    Perm Link:   PYTHON - Hash Test using SHA512



James Conner