Google
 
Web pyadmin.blogspot.com

Friday, September 08, 2006

A tricky secure bulk file upload

Last week i came across a situation that, I hav to upload a bulk file of 52 MB through a very unsteady internet connection.This python program is for that,which splits a files into pieces and do an secure copy and reconstruct the file there,at the destination.This script uses the python implementation of expect command in unix,namely pexpect.This is a very useful class,which can be used to execute almost all commands and we can spawn a new process and we can control the session of the process through this class.
here's the script


#!/usr/bin/python
import pexpect
import os
import sys
import getpass

failedlist=[]
def splitter (filename,size,prefix):
os.popen('split -a3 -b %s %s %s'%(size,filename,prefix))
fin,fout=os.popen2('ls %s*'%(prefix))
list=fout.readlines()
return list
def doSsh (user, host, password, command):
"""This runs a command on the remote host. This returns a
pexpect.spawn object. This handles the case when you try
to connect to a new host and ssh asks you if you want to
accept the public key fingerprint and continue connecting.
"""
ssh_newkey = 'Are you sure you want to continue connecting'
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if i == 0: # Timeout
print 'ERROR!'
print 'SSH could not login. Here is what SSH said:'
print child.before, child.after
return None
if i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
child.expect ('password: ')
i = child.expect([pexpect.TIMEOUT, 'password: '])
if i == 0: # Timeout
print 'ERROR!'
print 'SSH could not login :'
print child.before, child.after
return None
child.sendline(password)
return child
def doScp(filename,user,host,passwd,dest_dir):
ssh_newkey = 'Are you sure you want to continue connecting'
print 'doing scp'
string='scp '+filename+' '+user+'@'+host+':'+dest_dir
print string
child = pexpect.spawn(string)
print 'after spawning'
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if i == 0: # Timeout
print 'ERROR!'
print 'Copying failed: '
print child.before, child.after
failedlist.append(filename)
return None
if i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
child.expect ('password: ')
i = child.expect([pexpect.TIMEOUT, 'password: '])
if i == 0: # Timeout
print 'ERROR!'
print 'Copying Failed :'
print child.before, child.after
return None
child.sendline(passwd)
child.expect([pexpect.TIMEOUT, '100%'])
print 'uploading done'
return child


def doUpload(list,user,passwd,host,dest_dir):
for file in list:
doScp(file,user,host,passwd,dest_dir)

list=splitter('install','1m','.splitted.tmp.')
doUpload(list,'root','password','192.168.1.2','/root/')
doSsh('root','192.168.1.2','password','cat .splitted.tmp.* > install')
doSsh('root','192.168.1.2','password','rm -f .splitted.tmp.*')



Wednesday, August 30, 2006

RANCID - Really Awesome New Cisco confIg Differ

RANCID -A great, simple ,light weight tool for system and network administrators.It's really awsome as it's name suggests.
Rancid is a combination of shell, Perl, and Expect scripts that work together to provide configuration management. Although the name implies Cisco-only support, the tool has grown to work with a multitude of devices from most major vendors. Adding extensions for new device classes is also fairly easy.
Rancid currently supports Cisco routers, Juniper routers, Catalyst switches, Foundry switches, Redback NASs, ADC EZT3 muxes, MRTd (and thus likely IRRd), Alteon switches, and HP Procurve switches and a host of others.

Tuesday, June 06, 2006

An interactive restore script

Im here again with a simple(useless?) utility which can simply restore specified files from a tar archive.You can specify some pattern and the program will show the file names starting with the specified pattern and u can select the required files from the archive and restore.That much simple.
The usage is as follows:
restore.py source.c /dev/nrtape
The code follows:

#!/usr/bin/python

# 'restore.py'. Invoke it as, for example,
# restore.py source.c /dev/nrtape
# to show all the archived files named 'source.c'
# which the user can select for retrieval.

import os,sys,Tkinter

try:
pattern = sys.argv[1]
archive = sys.argv[2]
except (IndexError,NameError):
print 'Usage:restore.py pattern archive'
sys.exit

def esf():
# Construct the string which lists all selected files,
# separated by a single blank. Use that string to
# specify the exact listof files to extract from the
# archive.
command = 'tar xf %s %s' % (archive,
' '.join([lb.get(index) for index in lb.curselection()]))
os.system(command)

# MULTIPLE so that we can select and extract several files in a
# single operation.
lb = Tkinter.Listbox(height = 12, width = 30, selectmode = Tkinter.MULTIPLE)
lb.pack()
Tkinter.Button(text = "Extract selected files", command = esf).pack()

# The "[:-1]" says, "ignore the trailing newline tar emits".
try:
for qualified_name in os.popen('tar tf %s' % archive).read().split('\n')[:-1]:
# Does the basename of this item match the pattern?
if os.path.basename(qualified_name).count(pattern) > 0:
lb.insert(Tkinter.END, qualified_name)
except NameError:
sys.exit
# Show the GUI panel.
Tkinter.mainloop()

Thursday, May 04, 2006

Problem faced with Nortel routers

As I am doing my work, I had came to one situation that, in evrymonth beginning I hav to change the password of 400 nortel routers within 2 days. Offcourse it's a very tedious task even with a 4 memberd team. Earlier it was very simple with cisco and juniper routers that a command like

for i in `cat file_containing_list_of_routers`

do
{
(echo "username" ; echo "password" ;
echo "term length 0";
cat commands_cisco.txt;
echo "exit";
echo "exit";
sleep 2 ) | telnet $i >> /verify.out

}
done
where ommands_cisco.txt contains the commads for changing password in a cisco/juniper router



will do the work. But when it's come to nortel routers, alas this thing is not working, I heard that this is bcos of some security mechanism implementd on nortel routers.There comes my shy friend

I am using the telnetlib module. The script reads the ip addresses from a file and changes the password.

#!/usr/bin/python
__author__ = 'Vineesh Kumar : vinu@hcl.in'
__version__ = '0.2'
__date__ = '7/04/06'

import getpass
import sys
import telnetlib
import time

sleeptime=15 """The time to wait for getting a response from the router"""

"""
Ok I will extract the input arguments
"""
def extractArgs(listofargs):
for arg in range(0,len(listofargs),2):
if listofargs[arg] == '-f':
file=listofargs[arg+1]
elif listofargs[arg]=='-u':
user=listofargs[arg+1]
elif listofargs[arg]=='-p':
password=listofargs[arg+1]
elif listofargs[arg] == '-n':
newpwd=listofargs[arg+1]
return [file,user,password,newpwd]

"""
It's my duty to read the IPS from a file specified by the -f switch
"""
def readIpsFromFile(filename):
fileHandle = open ( filename )
fileList = fileHandle.readlines()
fileHandle.close()
return fileList

"""
reads the ip from the list and change the password
"""
def changeAll(hostlist,user,passwd,newpasswd):
for host in hostlist:
if host.strip():
changePassword(host,user,passwd,newpasswd)

"""
The actual worker who changes the password by telnetting to
a specified ip
"""
def changePassword(host,user,passwd,newpasswd):
HOST=host
user=user
password=oldpwd=passwd
newpwd=newpasswd
try:
if HOST.strip():
tn = telnetlib.Telnet(HOST)
print tn.read_until("Login:")
tn.write(user + "\n")
if password:
print tn.read_until("Password:",120)
tn.write(password + "\n")
if tn.read_until(">",120):
tn.write("bcc\n")
print tn.read_until("bcc>",120)
tn.write("password\n")
print tn.read_until("password:",120)
time.sleep(sleeptime)
tn.write(oldpwd+ "\n")
time.sleep(sleeptime)
tn.write(newpwd + "\n")
time.sleep(sleeptime)
tn.write(newpwd + "\n")
tn.write("exit")
tn.write("logout")
tn.close()
print "Password changed successfully for device: " + host +"\n"
else:
print "Password changing failed for device :"+ host + "\n"
except EOFError:
print "Username/Password mismatch for device :"+ host + "\n"

"""
I am the master I will call others to do the job
"""
def doTheJob():
try:
list=extractArgs(sys.argv[1:])
ips=readIpsFromFile(list[0])
print ips
changeAll(ips,list[1],list[2],list[3])
except UnboundLocalError:
print "usage: chpwd -f -u -p -n "

"""
I am the admin and ultimately I am executing this program
"""

doTheJob()




and
That may not be the end of the story.........
The hunt begins

Tuesday, May 02, 2006

An admin friendly ping

When i was working, I just want to ping some machines.And offcourse the machines are from other networks(otherwise i can use broadcast).So one way i found is that i can write a simple shell script which does the ping to the individual systems, but what about if u are having some 100 systems and all takes time more that 2 seconds to get a response?
here comes an alternative!!!!! a threaded ping, offcourse using python
#!/usr/bin/python
import os
import re
import time
import sys
from threading import Thread

class ping(Thread):
def __init__ (self,ip):
Thread.__init__(self)
self.ip = ip
self.status = -1
def run(self):
pingseq = os.popen("ping -q -c2 "+self.ip,"r")
while 1:
line = pingseq.readline()
if not line: break
result = re.findall(ping.getstatus,line)
if result:
self.status = int(result[0])

ping.getstatus = re.compile(r"(\d) received")
output = ("Not responding","Partial Response","Responding")

print time.ctime()

pinglist = []

for host in range(100,120):
ip = "10.200.9."+str(host)
current = ping(ip)
pinglist.append(current)
current.start()

for pingle in pinglist:
pingle.join()
print "Status from ",pingle.ip,"is",output[pingle.status]

print time.ctime()

some fun with python

Here is a python script for sending email.U may wonder y i need another mail sender. No u don't need one.
but if u just want to play on ur friend by shooting some funny emails without revealing ur identity, u need this one. say if u want to play around a friend pretending as a (fe)male, u can use this script to send him/her an email as sexy(fe)male@heaven.com

Guyz!!!(who thinks pyton in for serious tasks),plz dont scold me. This is meant for newbies.This script reveals the power of python. A newbe can understand this script.

This is a command line tool, and moreover u dont need an email account to send mail to someone. But offcourse u need a mail server,and u cannot recieve get any reply in this (noexistent)email id. This is not a really useful tool. This is for those who are just into python and also to demonstrate the power of python.

#!/usr/bin/python

import smtplib, string, sys, time
"""IP/hostname of ur mail server"""
mailserver = "10.200.9.99"

From = string.strip(raw_input("From: "))
To = string.strip(raw_input("To: "))
Subject = string.strip(raw_input("Subject: "))

Date = time.ctime(time.time())
Header = ("From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n"
% (From, To, Date, Subject))


Text = "your message here"
server = smtplib.SMTP(mailserver)
failed = server.sendmail(From, To, Header + Text)
server.quit()
if failed:
print "failed to send mail"
else:
print "all done.."

First words

Here is the first posting of mine. this is just for testing the look and feel