Tuesday, April 27, 2010

DOS: Creation of HardLink in Windows

Problem Statement:
Creation of hardink in Windows

Solution:

This could be achieved by running the following on DOS prompt:
fsutil hardlink create c:\hlink.txt c:\log.log

Output of this command is:
Hardlink created for c:\hlink.txt <<===>> c:\log.log

Thus hlink.txt file is now a hardlink file for log.log.
Any changes made in log.log would reflect in hlink.txt file and vice-versa.
Also if any one file is deleted the other can be used as all contents would still be present in the other file.

Monday, April 26, 2010

DOS: Createfile of user-defined size

Hi Guys,

Here's something on our own, tried, tested and approved DOS commands.

Recently I came across a dos command that can create files of sizes that user needs. I thought this was useful and can used for:
- Creation of files as a test data
- Automation purposes based on the requirements
- For loading/stressing hard disk
- Boundary Value testing (since files can be craeted with least count of 1 Byte)
(Contributions by Sunil Ubranimath)

DOS Command:
fsutil file createnew c:\test.txt 2000

This creates a file test.txt on C:\ of 2000 Bytes. The data in the file is nothing but 'whitespaces'.


Other useful DOS commands:
C:\Documents and Settings\Chetan>fsutil
---- Commands Supported ----

behavior - Control file system behavior
dirty - Manage volume dirty bit
file - File specific commands
fsinfo - File system information
hardlink - Hardlink management
objectid - Object ID management
quota - Quota management
reparsepoint - Reparse point management
sparse - Sparse file control
usn - USN management
volume - Volume management

Sunday, April 25, 2010

Python: Command Design Pattern

Hi Guys,

Recently I was working on learning design patterns in python. If you are not reading them , I highly recommend you to do so...they definitely help you in creating better designs or frameworks.

Here's something on Command Design Pattern:

class CommandPattern:
def __init__(self, cmd):
self.cmd = cmd
self._dict = { 'add' : 'add()', 'sub' : 'sub()' }
if self._dict.has_key(cmd):
call = self._dict[cmd]
call = "self." + call
eval(call)
else:
print "Invalid Command...."
def add(self):
print "In Add"
def sub(self):
print "In Sub"
cmdpattern = CommandPattern('add')

Explaination:
Command design pattern is seen as an example of encapsulation.

As per wikipedia, Three terms always associated with the command pattern are client, invoker and receiver. The client instantiates the command object and provides the information required to call the method at a later time. The invoker decides when the method should be called. The receiver is an instance of the class that contains the method's code.

In the above example, based on the command that is passed to the construtor of the class, the corresposnding function of the class is called and executed.

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!