Category Archives: Scripts
PowerShell: Get File Version Info
$files = get-childitem $args -recurse -include *.dll,*.exe
if($files -eq $null)
{
Write-Host "No Exe or dll files present in the folder";
}
else
{
foreach ($i in $files)
{
$ver = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($i).FileVersion
if($ver -eq $null)
{
$i.FullName | Out-File NoVersion.txt -append
}
else
{
"{0}`t{1}"-f $i.FullName, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($i).FileVersion | out-file Version.xls -append
}
}
}
PowerShell: Clear Event logs from Windows machine
Problem Statement:
Need to clear off Application, Security and System Event logs of your Windows PC? Well here’s the solution.
foreach($computer in $args) { $ALive=get-wmiobject win32_pingstatus -Filter "Address='$computer'" | Select-Object statuscode if($ALive.statuscode -eq 0) { $logs = [System.Diagnostics.Eventlog]::GetEventLogs("$computer") $Applogs = $logs|where-object {$_.logdisplayname -eq "Application"} $Applogs.clear() $Securitylogs = $logs|where-object {$_.logdisplayname -eq "Security"} $Securitylogs.Clear() $Systemlogs = $logs|where-object {$_.logdisplayname -eq "System"} $Systemlogs.Clear() write-host Event logs cleared at $computer -background "GREEN" -foreground "BLACk" sleep 1 } else { write-host $computer is NOT reachable -background "RED" -foreground "BLACk" write-host "`nCheck if the system is Online `n" sleep 1 } }The Script requires computer ip or computer names passed as Command Line Arguments.
Python: Working with Dynamic Link Library (dll)
from ctypes import *
libc = windll.LoadLibrary('C:\\Windows\\kernel32.dll'')
x = libc.GetModuleHandleA ()
print x #Prints the object
del libc #Deletes the handle
Python: Profiler for scripts and libraries
Problem Statement:
import wmi
import os
import time
import string
__DELAY = 20
class Services:
"""
1. The Service Class is aimed at starting and stopping the services based on the service name given as an input.
2. __init__() - gets the name of the service
3. getstatus() - gets the status of the services - Running or Stopped.
4. 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)
time.sleep(__DELAY)
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()
time.sleep(__DELAY)
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)
time.sleep(__DELAY)
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()
time.sleep(__DELAY)
except Exception:
raise
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.
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?
Solution
class Add: 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.
Perl: Signal Handling
Problem Statement:
If you have been using PERL for a long time now, you must be cognizant of the fact that, if you see your program behaving in an unexpected/bizarre way, pressing Ctrl+C would help you to stop the program execution. But did you know, you can disable this functionality. By disable, I mean that, even after pressing Ctrl+C, your program won’t stop executing. Sure, this would have kindled your thinking caps!! Let’s see how we can achieve it.
Solution:
This could be easily accomplished by scripting a single line at the onset of your program.
$SIG{‘INT’} = ‘IGNORE’;
But how do you check it? For checking, try this piece of code:
$SIG{‘INT’} = ‘IGNORE’;
@arr = (0..10);
foreach (@arr) {
print(“$_\n”);
sleep 1;
}
While the code snippet is getting executed, if you pres Ctrl+C, it would not stop your program.
This worked on Windows XP for me….Cool!! Isn’t it??
Let’s say, instead of ignoring Ctrl+C, you want to achieve something else when Ctrl+C is pressed. Like, say you want the program to print some message or exit. This is how it can be done:
sub INT_handler { #function starts
print(“Don’t Interrupt!\n”);
#exit(0); – similar to print, program can be exited using exit(0)
}
$SIG{‘INT’} = ‘INT_handler’;
@arr = (0..10);
foreach (@arr) {
print(“$_\n”);
sleep 1;
}
While the program execution happens, pressing Ctrl+C will print “Don’t Interrupt!”
But beware, if again Ctrl+C is pressed, the program execution stops. This worked on Windows XP for me.
Underlying facts:
Basically Ctrl+C is a signal that is sent to the program. So when Ctrl+C sequence is pressed, a signal called INT is activated. When we say $SIG{‘INT’} = ‘IGNORE’, we basically ignore this signal and hence it doesn’t affect program execution.
Similar to INT, we have many more signals. In order to see these, you can run this code:
foreach (keys %SIG) #%SIG is actually a hash that stores all signals like %ENV that stores environment variables.
{ print ” $_ \n”; } #lists all the signals supported by the platform.
You are now free to play around with these….Enjoy!!
Python: Using SendKeys
Problem Statement:
import SendKeys
import subprocess
password = "PASSWORD"
command = "runas /user:USERNAME Notepad.exe"
subprocess.Popen(command)
send = """
%s{ENTER}
""" % (password)
SendKeys.SendKeys(send)
PowerShell: Getting inventory details
Problem Statement:
I have a lot of servers on my network and my manager comes and tell me, “Can you get me details like the total RAM, HDD, Manufacturer, Serial Number and ServerName of all these servers?? I need to report this to Infrastructure team! Please get this in 2 hours time!!” Sounds laborious..Isn’t it??
Here's the script:
"IP`tHardDisk`tRAM`tSystemName`tManufacturer`tSerialNumber" out-file C:\Results.csv -append Function HDDInfo { param($ip) $alldrives = get-wmiobject win32_logicaldisk -filter "DriveType=3" -computername $ip $HDD = 0 foreach ($i in $alldrives) { $HDD = $HDD + ($i.size)/(1gb) } $HDD } Function RAMInfo { param($ip) $ram = get-wmiobject win32_ComputerSystem -computername $ip $RAM = ($ram.TotalPhysicalMemory)/(1gb) $RAM } Function SystemName { param($ip) $bios = get-wmiobject win32_bios -computer $ip $bios.name } Function Manufacturer { param($ip) $bios = get-wmiobject win32_bios -computer $ip $bios.manufacturer } Function SerialNumber { param($ip) $bios = get-wmiobject win32_bios -computer $ip $bios.SerialNumber } $address = "10.2.2." 2..254 foreach-object { $ip = $address + $_ $ping = get-wmiobject win32_pingstatus -filter "Address = '$ip'" select-object statuscode if($ping.statuscode -eq 0) { $HDD = HDDInfo $ip sleep 1 $RAM = RAMInfo $ip sleep 1 $SystemName = SystemName $ip $Manufacturer = Manufacturer $ip $SerialNumber = SerialNumber $ip "$ip`t$HDD`t$RAM`t$SystemName`t$Manufacturer`t$SerialNumber" out-file C:\Results.csv -append } else { "$ip is Offline or Not Reachable.." out-file C:\Results.csv -append } }In this script, I assume all your systems on the network are
in the IP range of 10.2.2.x and
I am collecting the details of IPs: 10.2.2.2 - 10.2.2.254
Run the script, wait for 4-5 minutes and get the results in Results.csv file.
![]()
Python: Threading Example
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.