Set archive bit on files in a directory

import win32file
import win32con
import os

def togglefileattribute(filename, fileattribute, value):
    """Turn a specific file attribute on or off, leaving the other
    attributes intact.
    """
    bitvector = win32file.GetFileAttributes(filename)
    if value:
        bitvector |= fileattribute
    else:
        bitvector &= ~fileattribute
    win32file.SetFileAttributes(filename, bitvector)

# Sample usage:
for file in os .listdir(r'C:\Temp\doc'):
    file = os.path.join(r'C:\Temp\doc\%s'%file)
    togglefileattribute(file, win32con.FILE_ATTRIBUTE_ARCHIVE, False)

Remote monitoring Windows

This script requests following informations remotely from a Windows machine:

  • Uptime
  • CPU Utilization
  • Available Memory
  • Memory Used
  • Ping

Attention: This script needs the WMI module from Tim Golden.

import re
import wmi
from subprocess import Popen, PIPE
# this script comes from http://coreygoldberg.blogspot.com/2008/12/python-monitor-windows-remotely-with.html


def get_uptime(computer, user, password):
    c = wmi.WMI(computer=computer, user=user, password=password, find_classes=False)
    secs_up = int([uptime.SystemUpTime for uptime in c.Win32_PerfFormattedData_PerfOS_System()][0])
    hours_up = secs_up / 3600
    return hours_up


def get_cpu(computer, user, password):
    c = wmi.WMI(computer=computer, user=user, password=password, find_classes=False)
    utilizations = [cpu.LoadPercentage for cpu in c.Win32_Processor()]
    utilization = int(sum(utilizations) / len(utilizations))  # avg all cores/processors
    return utilization

    
def get_mem_mbytes(computer, user, password):
    c = wmi.WMI(computer=computer, user=user, password=password, find_classes=False)
    available_mbytes = int([mem.AvailableMBytes for mem in c.Win32_PerfFormattedData_PerfOS_Memory()][0])
    return available_mbytes


def get_mem_pct(computer, user, password):
    c = wmi.WMI(computer=computer, user=user, password=password, find_classes=False)
    pct_in_use = int([mem.PercentCommittedBytesInUse for mem in c.Win32_PerfFormattedData_PerfOS_Memory()][0])
    return pct_in_use
    
    
def ping(host_name):
    p = Popen('ping -n 1 ' + host_name, stdout=PIPE)
    m = re.search('Average = (.*)ms', p.stdout.read())
    if m:
        return True
    else:
        raise Exception 

Change Desktop color with ctypes

from ctypes.wintypes import windll, c_int, byref, RGB
COLOR_BACKGROUND = 1 # from winuser.h or win32con
SetSysColors = windll.user32.SetSysColors
which_color = RGB(255,0,0) # red
SetSysColors(1, byref(c_int(COLOR_BACKGROUND)), byref(c_int(which_color)))

Remote calls to a windows maschine

Here http://coreygoldberg.blogspot.com is another script to remotely get

  • Uptime
  • CPU Utilization
  • Available Memory
  • Memory Used
  • Ping

with Python and the wmi module. Simply drop the wmi module and the script into a directory and import it from a separate script or i.e. add a

get_cpu("maschine_name")

.

Here is the source code:

import re
import wmi
from subprocess import Popen, PIPE



def get_uptime(computer, user, password):
    c = wmi.WMI(find_classes=False, computer=computer, user=user, password=password)
    secs_up = int([uptime.SystemUpTime for uptime in c.Win32_PerfFormattedData_PerfOS_System()][0])
    hours_up = secs_up / 3600
    return hours_up


def get_cpu(computer, user, password):
    c = wmi.WMI(find_classes=False, computer=computer, user=user, password=password)
    utilizations = [cpu.LoadPercentage for cpu in c.Win32_Processor()]
    utilization = int(sum(utilizations) / len(utilizations))  # avg all cores/processors
    return utilization

    
def get_mem_mbytes(computer, user, password):
    c = wmi.WMI(find_classes=False, computer=computer, user=user, password=password)
    available_mbytes = int([mem.AvailableMBytes for mem in c.Win32_PerfFormattedData_PerfOS_Memory()][0])
    return available_mbytes


def get_mem_pct(computer, user, password):
    c = wmi.WMI(find_classes=False, computer=computer, user=user, password=password)
    pct_in_use = int([mem.PercentCommittedBytesInUse for mem in c.Win32_PerfFormattedData_PerfOS_Memory()][0])
    return pct_in_use
    
    
def ping(host_name):
    p = Popen('ping -n 1 ' + host_name, stdout=PIPE)
    m = re.search('Average = (.*)ms', p.stdout.read())
    if m:
        return True
    else:
        raise Exception  

Export variables on win32 like in Unix

This script comes from Activestate. It exports a variable permanently on win32 – without needing to reboot the system. Note: pywin32 must be installed to run the script.

Use it like this:

import win32export
win32export.export("fooname" , "foovalue")

And here comes the script. Save it as win32export.py and use it from other scripts or from the command line.

"""
vim: set enc=utf-8

Author :  winterTTr
Mail   :  winterTTr (at) gmail.com
Desc   :  Tools for Operation on Win32 Environment variables
Module :  win32export.py
"""

import win32gui
import win32con
import win32api

def export ( name , value , update_system = True ):
    try :
        modifyVariableInRegister( name , value )
    except:
        return False

    if update_system :
        updateSystem()

    return True

def modifyVariableInRegister( name , value ):
    key = win32api.RegOpenKey( win32con.HKEY_CURRENT_USER,"Environment",0,win32con.KEY_ALL_ACCESS)
    if not key : raise
    win32api.RegSetValueEx( key , name , 0 , win32con.REG_SZ , value )
    win32api.RegCloseKey( key )

def updateSystem():
    rc,dwReturnValue = win32gui.SendMessageTimeout( win32con.HWND_BROADCAST , win32con.WM_SETTINGCHANGE , 0 , "Environment" , win32con.SMTO_ABORTIFHUNG, 5000)

Alarm clock on a Windows machine

Following example comes from Activestate (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/510387) and represents an alarm clock on Windows:

try:
    import os
    import sys
    import time
    import msvcrt
    import winsound
except ImportError, error:
    sys.stdout.write('ImportError: %s' % error)
    sys.exit(1)

def main():
    try:
        arg = time.strptime(sys.argv[1], '%H:%M')
        arg_sec = (arg.tm_hour * 60 + arg.tm_min) * 60
        now = time.localtime()
        now_sec = (now.tm_hour * 60 + now.tm_min) * 60 + now.tm_sec
        alarm(arg_sec - now_sec + (86400 if arg_sec <= now_sec else 0))
    except:
        sys.stdout.write(os.path.basename(sys.argv[0]))
        sys.stdout.write(' HH:MM')

def alarm(seconds):
    time.sleep(seconds)
    while msvcrt.kbhit():
        msvcrt.getch()
    while not msvcrt.kbhit():
        winsound.Beep(440, 250)
        time.sleep(0.25)

if __name__ == '__main__':
    main()

Create Windows users

A simple script to create a user on Windows with Python

import win32netcon, win32net
d={}
d['name'] = "PythonTestUser"
d['password'] = "Top Secret"
d['comment'] = "A user created by some Python demo code"
d['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
d['priv'] = win32netcon.USER_PRIV_USER
win32net.NetUserAdd(None, 1, d)

Copy big files on Windows

A short Python script (from Activestate) to copy very big files on Windows:

import win32file

def copy_big_file(srcname, dstname):
        hin= win32file.CreateFile(
                srcname,
                win32file.GENERIC_READ,
                0, # win32file.FILE_SHARE_READ,
                None,
                win32file.OPEN_EXISTING,
                win32file.FILE_FLAG_SEQUENTIAL_SCAN,
                0)
##        print "type of hin=%r" % type(hin)
        hou= win32file.CreateFile(
                dstname,
                win32file.GENERIC_WRITE,
                0, # win32file.FILE_SHARE_READ,
                None,
                win32file.CREATE_ALWAYS,
                win32file.FILE_FLAG_SEQUENTIAL_SCAN,
                0)
        while 1:
                rc, buffer= win32file.ReadFile(hin, 65536)
                if not buffer: break
                if rc == 0:
                        win32file.WriteFile(hou, buffer)
                else:
                        print "rc=%d" % rc
                        break
        hin.Close()
        hou.Close()

Find all Windows Shell Folder (Special Folder) Locations

Quick method to find the location of the current user’s special folders and return them in a dictionary keyed on the folder name.

Two ways below to enum all the shell folder registry keys. The for loop version shown is safer. The while components are there but commented out, just note that it relies on an exception error to indicate the end of the key has been reached, so there is a small chance that some unknown condition could cause it to never terminate, so the for loop is safer.

user_dict = Get_User_ShellFolders()
print user_dict

def Get_User_ShellFolders():
    # Routine to grab all the Windows Shell Folder locations from the registry.  If successful, returns dictionary
    # of shell folder locations indexed on Windows keyword for each; otherwise, returns an empty dictionary.
    import _winreg
    return_dict = {}

    # First open the registry hive
    try:
        Hive = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
    except WindowsError:
        print "Can't connect to registry hive HKEY_CURRENT_USER."
        return return_dict

    # Then open the registry key where Windows stores the Shell Folder locations
    try:
        Key = _winreg.OpenKey(Hive, "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
    except WindowsError:
        print "Can't open registry key Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders."
        _winreg.CloseKey(Hive)
        return return_dict

    # Nothing failed above, so enumerate through all the Shell Folder values and return in a dictionary
    # This relies on error at end of 
    try:
        #i = 0
        #while 1:
        for i in range(0, _winreg.QueryInfoKey(Key)[1]):
            name, value, val_type = _winreg.EnumValue(Key, i)
            return_dict[name] = value
            i += 1
        _winreg.CloseKey(Key)                           # Only use with for loop
        _winreg.CloseKey(Hive)                          # Only use with for loop
        return return_dict                              # Only use with for loop
    except WindowsError:
        # In case of failure before read completed, don't return partial results
        _winreg.CloseKey(Key)
        _winreg.CloseKey(Hive)
        return {}

Example Output:

{
        'Templates': u'C:\\Documents and Settings\\username\\Templates', 
        'Cookies': u'C:\\Documents and Settings\\username\\Cookies', 
        'Fonts': u'C:\\WINNT\\Fonts', 
        'PrintHood': u'C:\\Documents and Settings\\username\\PrintHood', 
        'AppData': u'C:\\Documents and Settings\\username\\Application Data', 
        'Programs': u'C:\\Documents and Settings\\username\\Start Menu\\Programs', 
        'Personal': u'C:\\Documents and Settings\\username\\My Documents', 
        'Local Settings': u'C:\\Documents and Settings\\username\\Local Settings', 
        'Cache': u'C:\\Documents and Settings\\username\\Local Settings\\Temporary Internet Files', 
        'Startup': u'C:\\Documents and Settings\\username\\Start Menu\\Programs\\Startup', 
        'Desktop': u'C:\\Documents and Settings\\username\\Desktop', 
        'Start Menu': u'C:\\Documents and Settings\\username\\Start Menu', 
        'NetHood': u'C:\\Documents and Settings\\username\\NetHood', 
        'Local AppData': u'C:\\Documents and Settings\\username\\Local Settings\\Application Data', 
        'Favorites': u'C:\\Documents and Settings\\username\\Favorites', 
        'SendTo': u'C:\\Documents and Settings\\username\\SendTo', 
        'History': u'C:\\Documents and Settings\\username\\Local Settings\\History', 
        'My Pictures': u'C:\\Documents and Settings\\username\\My Documents\\My Pictures', 
        'Recent': u'C:\\Documents and Settings\\username\\Recent'
}

Get List of IP Routes

Quick method to extract the IP routing table on a PC into a list of lists using a single list comprehension.

Each route table entry is stored in a list where:

[0] = Network Destination
[1] = Netmask
[2] = Gateway
[3] = Interface
[4] = Metric

The active default route will always be the first list in the results [0], so the default next hop for unknown destinations will be [0][3].

from os import popen
from string import split, join
from re import match

rtr_table = [elem.strip().split() for elem in popen("route print").read().split("Metric\n")[1].split("\n") if match("^[0-9]", elem.strip())]

print "Active default route:", rtr_table[0]

print "Active default next hop:", rtr_table[0][3]

The above comprehension relies on the “Metric” header value. I later realized this may not scale to non-U.S. PCs so here’s a different comprehension that should work for all regions.

[elem.strip().split() for elem in popen("route print").read().split("\n") if match("^[0-9]", elem.strip()) and is_IPv4_Addr(elem.strip().split()[0])]

Important: The above comprehensions don’t take into account that “route print” may be invalid on some PCs…though I’ve never seen this in practice. So you may want to capture the popen output first and check to make sure it’s not blank so the comprehension doesn’t throw an exception.

    return_vals = popen("route print").read()
    if return_vals:
        # U.S. Version
        #rtr_table = [elem.strip().split() for elem in return_vals.split("Metric\n")[1].split("\n") if match("^[0-9]", elem.strip())]

        # Universal Version ?
        return [elem.strip().split() for elem in return_vals.split("\n") if match("^[0-9]", elem.strip()) and is_IPv4_Addr(elem.strip().split()[0])]