Friday, November 12, 2010

PyRebootOps

Introduction

Often in Windows systems we observe that move or delete operations can’t be executed on a file if it’s locked. Files can get locked if different processes start accessing it or if the file has already been loaded in RAM.

Such problems can be resolved by scheduling file operations for the next system restart before the processes or services start and set locks on the files.

PyRebootOps is a Python utility that uses windows mechanism for scheduling operations on a file so that these operations can be executed during next system restart.

PyRebootOps

* Schedules – Move, Rename, Delete operations on locked files.
* View and Reset scheduled operations.
* Restart the user system.

PyRebootOps Help

***********************************************************
PyRebootOps1.0: Schedule file opeartions to be executed
during the next system reboot. – Chetan Giridhar
***********************************************************

syntax: PyRebootOps.exe [...]

-move: Moves a file from source to destination.
and are required.

-delete: Deletes the file from the harddisk after reboot.
not required.

-rename: Renames a file.
and are required.

-scheduled: Prints all the scheduled operations for the next reboot.

-reset: Resets all the operations that were previously scheduled.

-reboot: Restarts the system after a timeout of 1 sec.

PyRebootOps on sourceforge

Wednesday, July 21, 2010

DOS: SystemInfo

Problem Statement:
Using DOS command to get all the information pertaining to the sytem.

Solution:
Use of Dos coammnd: systeminfo.
Below is a typical output of systeminfo command on DOS prompt.


Using Perl Script to get OS Name:
use strict;
system("systeminfo find \"OS Name\" > C:\\temp\\temp.txt");
open(FH, "<", "C:\\temp\\temp.txt");
my $contents = ;
my @osInfo = split(':', $contents);
$osInfo[1] = s/\s\s+//g;
print $osInfo[1];

#This script would print the OS Name. Like it would print "Microsoft Windows 7 Utlimate" if run on Windows 7 - Ultimate Version of OS.

Tuesday, July 13, 2010

Perl: Using WMI in Perl

Problem Statement: Using WMI in Perl

Solution:

use Win32::OLE;

$instances = Win32::OLE->GetObject("winmgmts:\\\\localhost\\root\\CIMV2")->InstancesOf(Win32_LogicalDisk) or die "Cant access WMI";

for my $proc (in $instances)

{

printf "%5d %7d \n", $proc->{ProcessId}, $proc->{WorkingSetSize};

}

More examples on: http://www.perlmonks.org

Friday, July 9, 2010

Python: Threading in Python

Problem Statement:
Demonstrate the usage of threading in python.

Scripts:
Let's consider an example where we have two scripts, one of them is the "main.py" script that can be considered as parent and the other that would run in threads "log.py".

Let's first take a look at
"log.py"
---------
import time

 class log:
  def __init__(self, times):
   self.times = times
   self._bOn = True

  def start(self):
   while (self._bOn):
    print "in start"
    time.sleep(self.times)


  def stop(self):
   self._bOn = False
   print "in stop"

log.py contains a class log with constructor that takes argument for time and sets the bOn variable to True.
start() - starts printing "in start" till the time bOn is True.
stop() - prints "in stop" when it is called. It would also stop the start() function as bOn is set to False now.

Now on to the parent script that would call log.py to run in thread.
"Main.py"
----------
import os
import log
import time
import thread

obj = log.log(5)

def startlog():
 print "in thread"
 obj.start()

thread.start_new_thread(startlog,())
time.sleep(11)
obj.stop()

Main.py, imports log.py with constructor argument as "5".
startlog() - prints "in thread" and then would call start() of log.py
startlog() is now run as a thread
Main script sleeps for 11 seconds and then
calls the stop() of log.py

Explanation:
In this example, when Main.py starts running, it imports log.py and sets the argument(time) of the constructor to 5. It then starts a thread for the function startlog() and goes to sleep for 11 seconds.
Now that a thread has started with startlog() function, it prints "in thread", then calls start() of log.py. Now that bOn is True, it prints "in start" and sleeps for 5 seconds as set by Main.py. After 5 seonds again it prints "in start".
During this time the Main.py is still sleeping. When 11 seconds pass by, Main.py comes out of sleep (log.py is still running though) and calls the stop() of log.py. Because of which, start() gets stopped as bOn is now set to False and it prints "in stop".
Thus we have seen, Main.py and log.py both ran in parallel and Main.py could control the execution of log.py as it was run in thread.

Friday, July 2, 2010

C++: Get Function Name inside the Function

Problem Statement:
Recently I faced a problem in C++ where I wanted to know the name of the function inside the function that was being called...Confused?! I meant, if I am writing the definition of function named Func(), I want to know the name "Func" inside the function.

Solution:
Solution is the use of printf("%s", __FUNCTION__);
The attribute __FUNCTION__ contains the name of the function which is being executed.
This is what we needed, isn't it?

Hope this helps!

Sunday, June 27, 2010

Python: Making Objects Callable

Problem Statement: Have you ever wandered if we could make an object callable? Yes, I mean just use the object name as if you were calling function! Intersted?
Here's a simple solution!

Solution:
class Add:
#class for addition
 def __init__(self, num1, num2):
  self.num1 = num1
  self.num2 = num2
  print "Sum of", self.num1, "and", self.num2, "is:"

 def __call__(self):
  return (self.num1 + self.num2)

add = Add(1,2)
print add()

Output:
Sum of 1 and 2 is:
3

Explanation:
In this example, when 'add' is created using add = Add(1,2), def __init__() is called, since the constructor is called while object is getting created.
Because of the attribute __call__, the object becomes callable and hence we could use as add(). when add() is used, def __call__() is called.

Hope it's clear!

Friday, June 25, 2010

Python: Knowing the path of the currently running script

Problem Statement:

When we deal with frameworks, how often do we have to import modules. And it doesn't stop there; there arises a need where the imported would in turn import an another module, right? Would debugging an error condition be easy in these cases. If you have dealt with frameworks before, you would definitely understand the complexity of finding the fault location (exact module where the fault lies). Often people using logging mechanisms where they print to a file and start debugging. Wouldn't it be simple if we have a single line of code, just to tell which module is currently running? Was the first module being run when error occurred or was it the second module?

Solution:

Solution to this problem is fairly simple. Use of __file__ attribute in python.

__file__ attribute gets you information on the currently running script/module. Let's demonstrate this with an example. Consider, we have a parent script Main.py which imports a module called Module.py. Codes would like these:

Main.py

import Module

from Module import method

print "We're in %r" %__file__

Module.method()

Module.py

def method():

  import os

  f = open("C:\\sample.txt", "w")

  f.write('This is a sample file')

  print "We're in %r" %__file__

  f.close()

  os.system("del C:\\sample.txt")

Now, if we run the parent script Main.py, on command prompt, the output that we get is:

Output:

C:\Python26>Main.py

We're in 'C:\\Python26\\Main.py'
We're in 'C:\\Python26\\Module.py'

When the Main.py was running, __file__ gave us the path of current running script, but when the Module.py was imported and then __file__ was used, it gave the path of the module, and not the path of the parent script.

Utility:

- We can easily find the path of the current running script.

- Also we can easily find out which module is currently being run. This helps in easy debugging.

Monday, June 14, 2010

Python: MVC Pattern Example

Problem Statement: Demonstarte with example, Model-View-Controller Design pattern.

Script:
import sqlite3

class MVCModel:
def request(self, id):
# Would query database...
conn = sqlite3.connect('querydb')
c = conn.cursor()
results = c.execute('''select name from data where id = %d''' %id)
conn.commit()
c.close()
for row in results:
name = row[0]
return { "id" : id, "name": name}

class MVCController:
def __init__(self):
self.model = MVCModel()
self.view = MVCView()

def main(self):
post = self.model.request(1)
self.view.show(post)

class MVCView:
def show(self, post):
print "%(id)s %(name)s" % post

Controller = MVCController()
Controller.main()

Consistent to MVC Pattern,
the model runs a business logic that pings a database for an id and gets the corresponding name,
the controller accepts the request, sends it to the model, receives the return data from model and communicates to the view,
and the view represents the return data.

You could find a similar example on stackoverflow.

Tuesday, June 1, 2010

DOS: Create a 0KB file

Problem Statement:
I want to create a 0KB file using a DOS Command.

Here's how to do it:
Just Run->cmd and type in

goto >> "Filepath"

Since goto doesn't lead to any code execution its a command that is successful and since there is no return of the goto command, there is no data added to the file and hence the filesize is 0KB. Solves the purpose!

Just a try!
One could try "cls >> "Filepath" "; but this doesn't work as it adds a binary character in the file to be created.

Monday, May 24, 2010

Perl: One liner for Search and Replace in Multiple Files

Problem Statment:
Want to search a nd replace a string in multiple files? That to in one line? Simple! Read ahead..

Solution:
Install Perl and use Perl single line execution ie perl -e
Here's the actual statement taht will do the trick:

perl -pi -i.back -e 's///g;' *.txt

Explaination:
perl.exe is of course required for you to run the script.
-p : runs over the complete files.
-i : edits the files required.
-e : execute the script.
-i.bak : this creates a back-up of the file that is opened for editing.
*.txt : Search and Replace operation works on all files with extension '.txt'.

Small Tip: this is an important interview question. Adds more interest to the post, isn't it? :)

Hope this helps!

Sunday, May 16, 2010

Kernel: Finding drivers that are not digitally signed

Problem Statement:
Finding drivers on a user system that are not digitally signed.

Solution:
Windows provides a tool that hist the nail on its head. File Signature Verification Tool by Windows helps the user to find files that are not digitally signed. Since we are interested in drivers, we could target a folder C:\Windows\System32\drivers and find all the driver (.sys) files that are not digitally signed.

Using File Signature Verification Tool:


StartUp:
1. Goto Start->Run.
2. Type in sigverif. This will start the tool (sigverif.exe) and a file signature
verification window pops-up.

Searching Options:
User can search files of specified extensions in a specified folder.
- Check the option that says "Lokk for other files that are not digitally signed"
Under Serach Options:
- Select the file type that can be used for scanning. (like *.sys, *.dll or*.*)
- Select the folder "Look in this folder" option by browsing to the location.
- Check "Include subfolders" for recursive directory listing.

Logging Options:
User can configure the logging options as follows:
- Check the "Save the file signature verification results to a log file"
Under logging options:
- Select "Append/Overwrite existing log file" to either append the results of differents tests in a log file or overwrite the log file for a new test that's triggered every time.
- Log file name: Mention the log file name with appropriate path. Note: Pathnames need not to have (\\) as escape sequences.

Running the tool:
After configuring the tool. click OK and press Start. The tool now starts scanning all the files in all the configured folders to find all the files matching the configuration criterion that are not digitally signed.

Report:
A report of the test is genetated in a log file (configured by user in logging options) that gibes information on:
- Files that are scanned with the folder structure path.
- Files that are digitally signed with information on:
* File Modified date.
* File Version Information, if available.
* Catalog file information in which the file can be found.
* Signing Authority.
- Files that could not be scanned.


Case Study:
Let's say we want to find all the drivers present in C:\Windows\System32\drivers folders and check if they are digitally signed or not. Here are some snapshots that depict the configuration required.

System Specs:
Running the test on WINXP SP3 32 bit system.
2 GB RAM and 320 GB HDD.

Searching Options:



Logging Options:



We have now configured the tool check:
- All the driver files
- Under C:\Windows\System32\drivers folder
- Log the results in SIGVERIF.TXT file.
- Running the tool would yield the results on a UI (in case of files that are not digitally signed) and in the log file.

Results of case Study:
While running the test for the case study, it found some drivers on my laptop that were not digitally signed. Here's a snapshot depicting the unsigned driver files.


Contents of SIGVERIF.TXT Log File:
********************************

Microsoft Signature Verification

Log file generated on 5/17/2010 at 9:59 AM
OS Platform: Windows 2000 (x86), Version: 5.1, Build: 2600, CSDVersion: Service Pack 3
Scan Results: Total Files: 237, Signed: 229, Unsigned: 7, Not Scanned: 1

User-specified search path: *.*
User-specified search pattern: C:\WINDOWS\system32\drivers

File Modified Version Status Catalog Signed By
------------------ ------------ ----------- ------------ ----------- -------------------
[c:\windows\system32\drivers]
1028_dell_lat_d820.m 2/25/2009 None Not Signed N/A
1394bus.sys 4/14/2008 2:5.1 Signed NT5.CAT Microsoft Windows Component Publisher
acpi.sys 4/14/2008 2:5.1 Signed NT5.CAT Microsoft Windows Component Publisher
acpiec.sys 4/14/2008 2:5.1 Signed NT5.CAT Microsoft Windows Component Publisher
aec.sys 4/13/2008 2:5.1 Signed NT5.CAT Microsoft Windows Component Publisher
aegisp.sys 2/25/2009 3.4.9.0 Not Signed N/A
afd.sys 8/14/2008 2:5.1 Signed KB956803.cat Microsoft Windows Component Publisher

Unscanned Files:
------------------
[c:\windows\system32\drivers]
sptd.sys The process cannot access the file because it is being used by another process.

Thus the user gets the information on all the Digitally Signed and Unsigned driver files.

Kernel: Finding drivers loaded on user system

Problem Statement:
Find all the drivers that are loaded on user system and get the information pertaining to code, initialiazed and un- initialiazed static data and driver paging.

Solution:
Drivers.exe, a tool from WinDDK helps the user in finding all the drivres that are loaded on user system.

Drivers tool can be found at C:\winddk\7600.16385.1\tools\Other\i386 location of Winddk once the kit is installed on your system.

Using the tool:
1. Go to the command prompt.
2. Browse to the location where drivers.exe is present.
3. Run the command: "drivers.exe >> C:\report.txt"

This will save the information on all the drivers that were loaded on the user system on the harddisk location C:\report.txt.

Information obtained from the tool:
ModuleName: Represents the driver filename.
Code: Indicates the non-paged code in the driver file in bytes.
Data: Represents the initialiazed static data of the driver file in bytes.
BSS: Un-initialized static data in the image. Generally initialized to 0 or NULL.
Paged: Represets the data that is paged by the driver, in Bytes.
Init: Indicates the data that is not needed after the driver is initialized. Represented inBytes.
LinkDate: Its the date when the driver was linked.

Drivers.exe Output:
------------------------------------------------------------------------------
ModuleName Code Data Bss Paged Init LinkDate
------------------------------------------------------------------------------
ntkrnlpa.exe 479232 106496 0 1183744 180224 Tue Feb 16 18:55:00 2010
hal.dll 35968 42496 0 30976 15488 Mon Apr 14 00:01:27 2008
KDCOM.DLL 2560 256 0 1280 512 Sat Aug 18 02:19:10 2001
BOOTVID.dll 5632 3584 0 0 512 Sat Aug 18 02:19:09 2001


Tool Utility:
1. The tool can be used to identify if a particular driver is loaded on the user system.
2. Could verify if a driver loads on different operating systems and in different modes like Normal or Safe operating modes.
3. User can run the tool twice with in specified time frame and compare the results to check if there are any issues loading a driver under test.

Supported OS:
I have used the tool on the following platforms and it works fine.
- WINXP SP3 x32
- WIN 7 Ultimate x32

Wednesday, May 5, 2010

Python: Get and Set FileAttributes

Problem Statement:
Getting and Setting File Attributes in python

Code Implementation:
import os, win32file, win32con, win32api
import sys

def Getfileattrib(filepath):
""" Will check for a particular attribute is enabled for a file or not"""
try:
attributes = []
attrib = win32file.GetFileAttributes(filepath)
if not os.path.isfile(filepath):
print filepath + ": File Not Found"
print "Exiting..."
sys.exit(1)
if((attrib & win32con.FILE_ATTRIBUTE_ARCHIVE)):
attributes.append("A")
if((attrib & win32con.FILE_ATTRIBUTE_SYSTEM)):
attributes.append("S")
if((attrib & win32con.FILE_ATTRIBUTE_HIDDEN)):
attributes.append("H")
if((attrib & win32con.FILE_ATTRIBUTE_READONLY)):
attributes.append("R")
return attributes
except Exception:
raise

def Setfileattrib(filepath, attributes):
""" Will set attributes for a file taking list of attributes in a list"""
try:
if not os.path.isfile(filepath):
print filepath + ": File Not Found"
print "Exiting..."
for attribute in attributes:
os.system("attrib +%s %s" % (attribute.upper(), filepath))
except Exception:
raise

TechTip: Windows Autologon using UI

My last post talks about how to enable logon using regitsry changes...
Here's something that can be done using an UI.

Steps:
1. Go to Run and type "cotrol userpassword2".
2. This would take you to "User Accounts" screen where all the users for your machine are listed.
3. Under this uncheck the option "user must enter a username and password to use this computer".
4. Click on "Apply", which will take you to "Automatically Logon" Screen.
5. Enter the Username and Password for the User you want to enable automatic logon.

And you are done!

You can get more methods on this at: http://www.logonexpert.com/freeautologon.html

Tuesday, May 4, 2010

DOS: Batch Script to enable Windows Logon through Registry

Problem Statement:
Script to enable Windows Logon through Registry changes.

Batch Script Contents:
REG ADD "HKLM\software\Microsoft\windows NT\CurrentVersion\Winlogon" /v DefaultUserName /t REG_SZ /d USERNAME /f
REG ADD "HKLM\software\Microsoft\windows NT\CurrentVersion\Winlogon" /v DefaultPassword /t REG_SZ /d PASSWORD /f
REG ADD "HKLM\software\Microsoft\windows NT\CurrentVersion\Winlogon" /v AuotAdminLogon /t REG_SZ /d 1 /f
REG ADD "HKLM\software\Microsoft\windows NT\CurrentVersion\Winlogon" /v ForceAutoLogon /t REG_SZ /d 1 /f **

**Note: Run the first three commands for Windows XP and above OS.
If working on Windows 2K use all the four commands.

Utility:
You could now use this script on the system where you want to enable auto logon.

You can get more methods on this at: http://www.logonexpert.com/freeautologon.html

Wednesday, April 28, 2010

Python: Profiler

Problem Statement:
Profiling your python script.
A profiler is a program that monitors performance of a program during run time and provides a lot of information on the program.
Yes a module in Python that can do it easily for you!

Solution - Case Study:
Let's profile the Service class that I posted just before this blog.

Steps:
1. On the cmd prompt goto the Python installation directory.
2. Execute the command: python.exe -m cProfile Services.py

Output of the profiler:

907 function calls (893 primitive calls) in 0.105 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :1()
1 0.000 0.000 0.000 0.000 :1(error)
1 0.000 0.000 0.000 0.000 :11(com_error)
1 0.000 0.000 0.000 0.000 :2(__init__)
1 0.000 0.000 0.000 0.000 CLSIDToClass.py:18()
1 0.000 0.000 0.000 0.000 CLSIDToClass.py:48(HasClass)
1 0.003 0.003 0.104 0.104 Services.py:1()
1 0.000 0.000 0.000 0.000 Services.py:8(Services)
1 0.000 0.000 0.000 0.000 __init__.py:116(CDispatch)
1 0.000 0.000 0.000 0.000 __init__.py:161(Constants)
1 0.000 0.000 0.000 0.000 __init__.py:164(__init__)
1 0.000 0.000 0.002 0.002 __init__.py:18(__WrapDispatch)
1 0.000 0.000 0.000 0.000 __init__.py:190(EventsProxy)
1 0.000 0.000 0.000 0.000 __init__.py:26(SetupEnvironment)
1 0.000 0.000 0.000 0.000 __init__.py:417(DispatchBaseClass)
1 0.000 0.000 0.035 0.035 __init__.py:46(GetObject)
1 0.000 0.000 0.000 0.000 __init__.py:493(CoClassBaseClass)
1 0.013 0.013 0.036 0.036 __init__.py:5()
1 0.000 0.000 0.035 0.035 __init__.py:83(Moniker)
1 0.002 0.002 0.022 0.022 __init__.py:9()
1 0.000 0.000 0.000 0.000 build.py:102(__init__)
1 0.003 0.003 0.003 0.003 build.py:11()
1 0.000 0.000 0.000 0.000 build.py:34(NotSupportedException)
1 0.000 0.000 0.000 0.000 build.py:388(VTableItem)
1 0.000 0.000 0.000 0.000 build.py:411(LazyDispatchItem)
1 0.000 0.000 0.000 0.000 build.py:413(__init__)
1 0.000 0.000 0.000 0.000 build.py:53(MapEntry)
1 0.000 0.000 0.000 0.000 build.py:84(OleItem)
1 0.000 0.000 0.000 0.000 build.py:87(__init__)
1 0.000 0.000 0.000 0.000 build.py:99(DispatchItem)
1 0.000 0.000 0.000 0.000 dynamic.py:110(Dispatch)
1 0.000 0.000 0.000 0.000 dynamic.py:131(MakeOleRepr)
1 0.000 0.000 0.000 0.000 dynamic.py:161(CDispatch)
1 0.000 0.000 0.000 0.000 dynamic.py:162(__init__)
1 0.009 0.009 0.012 0.012 dynamic.py:17()
1 0.000 0.000 0.000 0.000 dynamic.py:79(_GetGoodDispatch)
1 0.000 0.000 0.000 0.000 dynamic.py:90(_GetGoodDispatchAndUserName)
1 0.000 0.000 0.000 0.000 fnmatch.py:11()
1 0.000 0.000 0.000 0.000 gencache.py:165(GetClassForCLSID)
1 0.000 0.000 0.000 0.000 gencache.py:204(GetModuleForCLSID)
1 0.005 0.005 0.008 0.008 gencache.py:22()
1 0.000 0.000 0.000 0.000 gencache.py:53(__init__)
1 0.000 0.000 0.000 0.000 gencache.py:73(_LoadDicts)
1 0.001 0.001 0.002 0.002 glob.py:1()
1 0.000 0.000 0.000 0.000 keyword.py:11()
5 0.000 0.000 0.000 0.000 ntpath.py:116(splitdrive)
1 0.000 0.000 0.000 0.000 ntpath.py:267(isdir)
1 0.000 0.000 0.000 0.000 ntpath.py:439(normpath)
1 0.000 0.000 0.000 0.000 ntpath.py:495(abspath)
4 0.000 0.000 0.000 0.000 ntpath.py:51(isabs)
3 0.000 0.000 0.000 0.000 ntpath.py:59(join)
1 0.003 0.003 0.022 0.022 pythoncom.py:2()
1 0.000 0.000 0.003 0.003 pywintypes.py:2()
2 0.003 0.002 0.019 0.009 pywintypes.py:3(__import_pywin32_system_module__)
2 0.000 0.000 0.004 0.002 re.py:186(compile)
2 0.000 0.000 0.004 0.002 re.py:227(_compile)
2 0.000 0.000 0.000 0.000 sre_compile.py:184(_compile_charset)
2 0.000 0.000 0.000 0.000 sre_compile.py:213(_optimize_charset)
6 0.000 0.000 0.000 0.000 sre_compile.py:24(_identityfunction)
2 0.000 0.000 0.000 0.000 sre_compile.py:264(_mk_bitmap)
2 0.000 0.000 0.001 0.000 sre_compile.py:367(_compile_info)
6/2 0.000 0.000 0.001 0.000 sre_compile.py:38(_compile)
4 0.000 0.000 0.000 0.000 sre_compile.py:480(isstring)
2 0.000 0.000 0.002 0.001 sre_compile.py:486(_code)
2 0.000 0.000 0.004 0.002 sre_compile.py:501(compile)
4 0.000 0.000 0.000 0.000 sre_parse.py:132(__len__)
36 0.000 0.000 0.000 0.000 sre_parse.py:136(__getitem__)
46 0.000 0.000 0.000 0.000 sre_parse.py:144(append)
6/2 0.000 0.000 0.000 0.000 sre_parse.py:146(getwidth)
2 0.000 0.000 0.000 0.000 sre_parse.py:184(__init__)
58 0.000 0.000 0.001 0.000 sre_parse.py:188(__next)
12 0.000 0.000 0.000 0.000 sre_parse.py:201(match)
53 0.000 0.000 0.001 0.000 sre_parse.py:207(get)
3/2 0.000 0.000 0.002 0.001 sre_parse.py:307(_parse_sub)
5/2 0.000 0.000 0.002 0.001 sre_parse.py:385(_parse)
2 0.000 0.000 0.002 0.001 sre_parse.py:669(parse)
2 0.000 0.000 0.000 0.000 sre_parse.py:73(__init__)
1 0.000 0.000 0.000 0.000 sre_parse.py:78(opengroup)
1 0.000 0.000 0.000 0.000 sre_parse.py:89(closegroup)
6 0.000 0.000 0.000 0.000 sre_parse.py:96(__init__)
2 0.000 0.000 0.000 0.000 struct.py:35(_compile)
2 0.000 0.000 0.000 0.000 struct.py:54(pack)
2 0.000 0.000 0.000 0.000 struct.py:77(unpack)
1 0.000 0.000 0.000 0.000 traceback.py:1()
1 0.000 0.000 0.000 0.000 winerror.py:4()
1 0.000 0.000 0.000 0.000 wmi.py:101(SelfDeprecatingDict)
1 0.000 0.000 0.000 0.000 wmi.py:1143(_wmi_watcher)
1 0.000 0.000 0.000 0.000 wmi.py:138(ProvideConstants)
1 0.000 0.000 0.000 0.000 wmi.py:144(__init__)
4 0.000 0.000 0.000 0.000 wmi.py:149(__getattr__)
1 0.000 0.000 0.000 0.000 wmi.py:168(x_wmi)
1 0.000 0.000 0.000 0.000 wmi.py:183(x_wmi_invalid_query)
1 0.000 0.000 0.000 0.000 wmi.py:187(x_wmi_timed_out)
1 0.000 0.000 0.000 0.000 wmi.py:191(x_wmi_no_namespace)
1 0.000 0.000 0.000 0.000 wmi.py:197(x_access_denied)
1 0.000 0.000 0.000 0.000 wmi.py:201(x_wmi_authentication)
1 0.000 0.000 0.000 0.000 wmi.py:205(x_wmi_uninitialised_thread)
1 0.000 0.000 0.000 0.000 wmi.py:324(_wmi_method)
1 0.000 0.000 0.000 0.000 wmi.py:432(_wmi_property)
1 0.000 0.000 0.000 0.000 wmi.py:450(_wmi_object)
1 0.000 0.000 0.003 0.003 wmi.py:733(_wmi_event)
1 0.000 0.000 0.000 0.000 wmi.py:756(_wmi_class)
1 0.005 0.005 0.101 0.101 wmi.py:77()
1 0.000 0.000 0.000 0.000 wmi.py:870(_wmi_result)
1 0.000 0.000 0.000 0.000 wmi.py:886(_wmi_namespace)
2 0.000 0.000 0.000 0.000 wmi.py:91(signed_to_unsigned)
2 0.000 0.000 0.000 0.000 {_sre.compile}
2 0.000 0.000 0.000 0.000 {_win32sysloader.GetModuleFilename}
1 0.001 0.001 0.001 0.001 {_win32sysloader.LoadModule}
2 0.000 0.000 0.000 0.000 {built-in method load}
1 0.000 0.000 0.000 0.000 {cPickle.Unpickler}
2 0.000 0.000 0.000 0.000 {dir}
1 0.001 0.001 0.105 0.105 {execfile}
2 0.000 0.000 0.000 0.000 {getattr}
2 0.000 0.000 0.000 0.000 {globals}
4 0.000 0.000 0.000 0.000 {hasattr}
2 0.000 0.000 0.000 0.000 {imp.get_suffixes}
2 0.015 0.007 0.015 0.007 {imp.load_dynamic}
1 0.000 0.000 0.000 0.000 {imp.new_module}
7 0.000 0.000 0.000 0.000 {isinstance}
171/169 0.000 0.000 0.000 0.000 {len}
3 0.000 0.000 0.000 0.000 {max}
4 0.000 0.000 0.000 0.000 {method 'Bind' of 'PyITypeComp' objects}
1 0.000 0.000 0.000 0.000 {method 'BindToObject' of 'PyIMoniker' objects}
1 0.000 0.000 0.000 0.000 {method 'GetContainingTypeLib' of 'PyITypeInfo' objects}
2 0.000 0.000 0.000 0.000 {method 'GetTypeAttr' of 'PyITypeInfo' objects}
1 0.000 0.000 0.000 0.000 {method 'GetTypeComp' of 'PyITypeInfo' objects}
1 0.000 0.000 0.000 0.000 {method 'GetTypeComp' of 'PyITypeLib' objects}
2 0.001 0.001 0.001 0.001 {method 'GetTypeInfo' of 'PyIDispatch' objects}
230 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'clear' of 'dict' objects}
1 0.000 0.000 0.000 0.000 {method 'close' of 'file' objects}
1 0.000 0.000 0.000 0.000 {method 'difference' of 'set' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
4 0.000 0.000 0.000 0.000 {method 'extend' of 'list' objects}
2 0.000 0.000 0.000 0.000 {method 'get' of 'dict' objects}
2 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects}
1 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects}
1 0.000 0.000 0.000 0.000 {method 'lstrip' of 'str' objects}
1 0.000 0.000 0.000 0.000 {method 'remove' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'replace' of 'str' objects}
1 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects}
7 0.000 0.000 0.000 0.000 {method 'startswith' of 'str' objects}
2 0.000 0.000 0.000 0.000 {method 'unpack' of 'Struct' objects}
15 0.000 0.000 0.000 0.000 {min}
1 0.000 0.000 0.000 0.000 {nt._getfullpathname}
1 0.000 0.000 0.000 0.000 {nt.stat}
1 0.000 0.000 0.000 0.000 {open}
46 0.000 0.000 0.000 0.000 {ord}
1 0.033 0.033 0.033 0.033 {pythoncom.MkParseDisplayName}
1 0.000 0.000 0.000 0.000 {win32api.GetFullPathName}
1 0.000 0.000 0.000 0.000 {win32api.GetTempPath}
1 0.000 0.000 0.000 0.000 {win32api.RegOpenKey}


So many function calls for a class! Wow!

More information on the profiler here



Tuesday, April 27, 2010

Python: Service Class

Problem Statement:
Create a class for starting, stopping and getting status of a service.

Uses 2 methods:
- Windows Management Instrumentation
- SC Command from DOS

Solution:

import wmi
import os
import time
import string

class Services:
"""
1. The Service Class is aimed at starting and stopping the services based on the service name given as an input.
2. Class is instantiated with Service Name with the help of argumented constructor called __init__().
3. Function getstatus() gets the status of the services - Running or Stopped.
4. Functions start(),stop() would start and stop the services respectively by first getting the status of the service.
5. If the service is already started/stopped, it will print a message that the service is already running/stopped.
6. start() and stop() functions work in 2 modes: Using DOS command SC and using Windows Management Instrumentation. Default mode being "SC".
"""
def __init__(self, service):
self.wmiObj = wmi.WMI()
self.service = service
def getstatus(self):
return self.wmiObj.Win32_Service(Name=self.service)[0].State
def start(self, mode="sc"):
if mode.upper() == "SC":
try:
if(self.getstatus() == "Running"):
raise Exception("%s service is already running " % self.service)
else:
command = 'sc.exe start ' + self.service
os.system(command)
except Exception:
raise
if mode.upper() == "WMI":
try:
if self.getstatus()=="Running":
raise Exception("%s service is already running " % self.service)
else:
self.wmiObj.Win32_Service(Name=self.service)[0].StartService()
except Exception:
raise

def stop(self, mode="sc"):
if mode.upper() == "SC":
try:
if(self.getstatus() == "Stopped"):
raise Exception("%s service is already stopped " % self.service)
else:
command = 'sc.exe stop ' + self.service
os.system(command)
except Exception:
raise
if mode.upper() == "WMI":
try:
if self.getstatus()=="Stopped":
raise Exception("%s service is already stopped " % self.service)
else:
self.wmiObj.Win32_Service(Name=self.service)[0].StopService()
except Exception:
raise




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!