Sunday, April 25, 2010

Python: VirtualMachine Handler

Problem Statement:
Create a Virtual Machine Handler class that supports,
- Start()
- Stop()
- TakeSnapshot()
- RevertSnapshot()

Solution:
import os
import time

class VirtualMCHandler:
"""
VirtualMCHandler class helps in managing Virtual Machines.
It has 4 functions that perform various operations on a VM.
Constructor: Takes the path of the Virtual Machine as its argument.
start() - Starts the Virtual Machine Image.
stop() - Stops the Virtual Machine Image.
takesnapshot(snapshotname) - Takes the Snaphot of Virtual Machine Image. Argument is the new snapshot name.
revertsnapshot(snapshotname) - Reverts the Virtual Machine Image to the previously taken snaphot name as mentioned in its argument.
"""


def __init__(self, VMPath):
self.path = "\"" + VMPath + "\""
def start(self):
_vmstart = "vmrun.exe -T ws start " + self.path + ""
os.system(_vmstart)

def stop(self):
_vmstop = "vmrun.exe -T ws stop " + self.path + ""
os.system(_vmstop)

def takesnapshot(self,snapshotname):
self.snapshotname = "\"" + snapshotname + "\""
_vmsnapshotname = "vmrun.exe -T ws snapshot " + self.path + " " + self.snapshotname
os.system(_vmsnapshotname)
def revertsnapshot(self,snapshotname):
self.snapshotname = "\"" + snapshotname + "\""
_vmrevert = "vmrun.exe -T ws revertToSnapshot " + self.path + " " + self.snapshotname
os.system(_vmrevert)

vm = VirtualMCHandler("E:\\Windows Server 2003 Enterprise Edition.vmx")
vm.start()
vm.takesnapshot("ARG")
vm.revertsnapshot("ARG")
vm.stop()

Note: You should have vmrun.exe in the path from where the script is run.
The script is tested for VMWare Workstation.

Python: SendKeys

Problem Statement:
Last week I faced an interesting problem t work. I was using runas DOS command using a Python script. After running the command, it asks you to enter a password on the cmd prompt. Now how do I do it with Python? Obvious answer was using subprocess functions (Popen and communicate). But have you tried something unconvenctional?

Solution:
SendKeys module could be the answer. Lets see how!
SendKeys is not available in Python 2.5 with default installation. One has to use that module by installing it.

Binary for the same could be obatainable from:

Here's the code that worked for me:

import SendKeys
import subprocess

password = "PASSWORD"
command = "runas /user:USERNAME Notepad.exe"
subprocess.Popen(command)

send = """
%s{ENTER}
""" % (password)

SendKeys.SendKeys(send)


For more better examples you could refer to:

Python: MD5/SHA Signature Class

Problem Statement:
Get a class to use it for calculatin signatures of file.

Solution Code:
class Hashes:
'''
Helps in retruning the foloowing signatures of a file:
md5()
sha1()
sha256()
sha512()
'''
def __init__(self, filepath):
self._filepath = filepath
def md5(self):
import md5
try:
fileobj = file(self._filepath, 'rb')
except Exception,msg:
raise
return md5.new(fileobj.read()).hexdigest()
def sha1(self):
import sha
try:
fileobj = file(self._filepath, 'rb')
except Exception,msg:
raise
return sha.new(fileobj.read()).hexdigest()
def sha512(self):
import hashlib
try:
fileobj = file(self._filepath, 'rb')
except Exception,msg:
raise
(hashlib.sha512()).update(fileobj.read())
return (hashlib.sha512()).hexdigest()
def sha256(self):
import hashlib
try:
fileobj = file(self._filepath, 'rb')
except Exception,msg:
raise
(hashlib.sha256()).update(fileobj.read())
return (hashlib.sha256()).hexdigest()

hash = Hashes("C:\\Windows\\system32\\notepad.exe")
hash.sha1()

Monday, April 12, 2010

Python: Load DLL

Hi guys,
Posting after a long time...but life had been busy and marriage really takes a toll on you. he he...jokes apart...
Meanwhile I have concentrated my energies on Python language. looks cool! Something in between Perl and C++ as I would like to put it.

Here's a small code that can show you the power of python:

Problem Statement:
What if you get a DLL file and you want to quickly test some of the exported APIs? Any ideas?

Solution:
Python provides you one.

Code snippet:
from ctypes import *
libc = windll.LoadLibrary('C:\\Windows\\System32\\kernel32.dll') #loads library
x = libc.GetModuleHandleA(None) #get the return type of GetModuleHandleA API
del libc #closes libc handler

In this code: we load kernel32.dll file and pass None argument to GetModuleHandleA function of the Dll.

Similarly you could customize this small code for your use.
Simple and quick!



Enjoy! Please do comment!

Wednesday, December 2, 2009

AutoIT: Mimic User Activities with Files

There was a need for us to perform some user activities while our servioces were running on a system. The activities would be pertaining to file and as below:
1. Opening an instance of excel, winword or wordpad.
2. Writing some text in the opened instance.
3. Saving the file with a filename on the C:\


Script:

Here's the AutoIT script that would perform the above mentioned operations in an excel sheet.

; Run Excel
Run("C:\Program Files\Microsoft Office\Office12\Excel.exe")

WinWaitActive("Microsoft Excel - Book1")
sleep(500)
Send("{F2}")
sleep(500)
;writing into excel
$i = 0
Do
Send("=rand()")
Send("{ENTER}")
$i = $i + 1
Until $i = 500

; Finished!

;saving the document
Send("!f")
sleep(500)
Send("a")
WinWaitActive("Save As")
sleep(500)
Send("C:\Excel")
Send("{ENTER}")
sleep(1000)
Send("!{F4}")



Friday, November 20, 2009

Auto Refresh

Half an hour ago I felt a need for refreshing my web page as the same used to time out every 20 minutes, if not refreshed.
I bet all of you must have faced this situation someday at your work or while browsing at home. Isn't it? Surely, if you are a customer of icicidirect.com. :-)

Here's something on the solution front:
Raghu and I arrived at 2 solutions, of course, as you must have guessed, they are browser dependent.

Let’s begin with IE:
There is a website called: http://www.pagereboot.com/ie/ that comes to our rescue.
For eg:
http://www.pagereboot.com/ie/?url=http://www.rediff.com/&refresh=5
Above URL can be divided into three components:
1. http://www.pagereboot.com is the host website.
2. www.rediff.com webpage that you want to refresh and keep it alive.
3. &refresh=5 that helps you to refresh every 5 seconds.
Points 2 and 3 would be parameters and can be configured based on requirements.

Trivial! Isn’t it?

Let’s check out Firefox:
Here are a few easy steps that can help you on a FF browser.
1. Go to Firefox browser instance and go to Tools -> Add-Ons.
2. Add-Ons -> Get Add-Ons and search for ReloadEvery.
3. Click on Add to Firefox button and let the plug-in get installed.
4. The browser would now automatically restart.
5. Open your webpage on the browser instance and right click on the page.
6. You would now see a new option getting added in the menu that says ‘Reload Every’.
7. Configure it as per your use and Enjoy!

Lengthier, but simple and clean.

Up to you, you can use any one....

Let us know if you find a cooler way!

Friday, September 25, 2009

PERL: Check dlls used in a process

Problem Statement:
Find whether named dll’s are injected into certain processes

Solution:
Perl script (CheckDllInjection.pl) would:
Read a configuration xml
Start monitoring the processes (added in the process tags) and
Check if the dlls (added in dll tags) are getting injected in these processes or not.
Report the results in a desired format.

Pre-requisites:
You need to have Perl installed on your system and XML::Simple module should be present.

Input:
DllConfig.xml would contain the processes (Process tag) to be monitored and the dll’s (Dll tags) that need to be checked for injection. (sample Dllconfig.xml attached). Perl script to be run from a location where dll file is present.

Output:
Output is a Results.csv file that would give out the results telling if the dlls were really injected in the processes with the values as YES/NO and results as PASS/FAIL.

Contents of DllConfig.xml file:

<configuration>
<test>
<test1>
<process>process1.exe</process>
<dll>abc.dll</dll>
<dll>xyz.dll</dll>
</test1>

<test2>
<process>process2.exe</process>
<dll>pqr.dll</dll>
<dll>lmnop.dll</dll>
<dll>cjg.dll</dll>
</test2>
</test>
</configuration>

Perl Script that works on Windows Platform:

#!/usr/bin/perl
use XML::Simple;
if(-e "Results.csv")
{
system "del Results.csv";
}
open(FP, "> Results.csv");
print FP "Process,DLL,Injected?,Result \n";

$xml = new XML::Simple;
$dllconfig = $xml->XMLin("DllConfig.xml"); #reached the Configuration tag
$test = $dllconfig->{Test}; #reached the Test tag
%tests = %$test;

#got all the processes and dlls
$count=0;
foreach my $k (keys %tests) {
$process = $test->{$k}->{Process};
$dll = $test->{$k}->{Dll};
if(ref($dll) eq 'ARRAY')
{
foreach $mydll (@$dll) #reading DLL files one by one
{
system "tasklist /M $mydll > C:\\$mydll.txt";

open(FH, "C:\\$mydll.txt");

$size = -s FH;
if(!$size) { print FP "$process,$mydll,NO,FAIL\n";}

while()
{
if($_ =~ m/.*$process.*/i)
{
print FP "$process,$mydll,YES,PASS\n";
$flag=1;
last;
}
else
{
$flag=0;
}
}
if(!$flag) {print FP "$process,$mydll,NO,FAIL\n";}
close FH;
system "del c:\\$mydll.txt";
}

}
else
{
system "tasklist /M $dll > C:\\$dll.txt";

open(FH, "C:\\$dll.txt");

$size = -s FH;
if(!$size) { print FP "$process,$dll,NO,FAIL\n";}

while()
{
if($_ =~ m/.*$process.*/i)
{
print FP "$process,$dll,YES,PASS\n";
$flag=1;last;
}
else
{
$flag=0;
}

}if(!$flag) {print FP "$process,$dll,NO,FAIL\n";}
close FH;
system "del c:\\$dll.txt";
}
}

close FP;