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)

Send email with Outlook and Python

A simple example to send emails via Outlook and Python win32com.

import win32com.client

s = win32com.client.Dispatch("Mapi.Session")
o = win32com.client.Dispatch("Outlook.Application")
s.Logon("Outlook2003")
    
Msg = o.CreateItem(0)
Msg.To = "recipient@domain.com"
    
Msg.CC = "more email addresses here"
Msg.BCC = "more email addresses here"
    
Msg.Subject = "The subject of you mail"
Msg.Body = "The main body text of you mail"
    
attachment1 = "Path to attachment no. 1"
attachment2 = "Path to attachment no. 2"
Msg.Attachments.Add(attachment1)
Msg.Attachments.Add(attachment2)
 
Msg.Send()

Read from Microsoft Access via DAO and Python

Simple Database access to Microsoft Access via DAO and Python on Windows.

import win32com.client
daoEngine = win32com.client.Dispatch('DAO.DBEngine.35')
db = 'c:\\test\\mydatabase.mdb'
daoDB = daoEngine.OpenDatabase(db)
query = 'SELECT * FROM my_table WHERE my_attribute = 'my_search_value'
daoRS = daoDB.OpenRecordset(query)
print daoRS
daoRS.Close()

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])]

List all environment variables on a computer

Script from Microsoft. Lists all environment variables on a computer.

import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Environment")
for objItem in colItems:
    print "Caption: ", objItem.Caption
    print "Description: ", objItem.Description
    print "Install Date: ", objItem.InstallDate
    print "Name: ", objItem.Name
    print "Status: ", objItem.Status
    print "System Variable: ", objItem.SystemVariable
    print "User Name: ", objItem.UserName
    print "Variable Value: ", objItem.VariableValue

Getting environment variables from registry

This script comes from ASPN (posted from Denis Barmenkov) and prints the environment variables got from the Windows registry (\\HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment).

# -*- coding: Windows-1251 -*-
'''
getenv_system.py

Get SYSTEM environment value, as if running under Service or SYSTEM account

Author: Denis Barmenkov 

Copyright: this code is free, but if you want to use it, 
           please keep this multiline comment along with function source. 
           Thank you.

2006-01-28 15:30
'''

import os, win32api, win32con

def getenv_system(varname, default=''):
    v = default
    try:
        rkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment')
        try:
            v = str(win32api.RegQueryValueEx(rkey, varname)[0])
            v = win32api.ExpandEnvironmentStrings(v)
        except:
            pass
    finally:
        win32api.RegCloseKey(rkey)
    return v

print 'SYSTEM.TEMP => %s' % getenv_system('TEMP')
print 'USER.TEMP   => %s' % os.getenv('TEMP')
print 'USER.PATH   => %s' % os.getenv('PATH')

iteration wrappers

Some simple iteration wrappers lotus notes:

from win32com.client import Dispatch
session = Dispatch('Lotus.NotesSession')

def iterateDocuments(view):
   """ wrapper for iterating documents from a view, fe:
       for doc in iterateDocuments(inbox): print doc.GetItemValue('Subject') """
   doc = view.GetFirstDocument()
   while doc:
      yield doc
      doc = view.GetNextDocument(doc)

def iterateDatabases(server, filetype=1247):
   """ wrapper for iterating databases from a server, fe:
       for db in iterateDatabases('server'): print db.Title """
   db = server.GetFirstDatabase(filetype)
   while db:
      yield db
      db = server.GetNextDatabase()

def iterateEntries(ACL):
   """ wrapper for iterating ACL entries for a database, fe:
   for entry in iterateEntries(db.ACL):
         if entry.IsPerson: print entry.Name"""
   entry = ACL.GetFirstEntry()
   while entry:
      yield entry
      entry = ACL.GetNextEntry(entry)

Comfortable Internet Explorer Automation

Do you want to automate Microsoft Internet Explorer more comfortable than ever with Python ? Then maybe PAMIE is helpful for you. PAMIE (Python Automation Module For Internet Explorer) is a free opensource Python win32com script for automation of Internet Explorer – Mainly designed for QA engineers with scripting ability.

>You can download PAMIE from http://sourceforge.net/projects/pamie

Here are some functionalities listed:

_frameWait - waits for user speficied frame document to load
_wait - wait for documetn to load
checkForFormName - check to see if a formname exists in the document
checkForFrameName -- check to see if a framename exists
ClickBtnImage - Clicks on an input type image button
ClickButton - Click on a button
ClickImage - clicks on an Image
ClickLink - Clicks on a link
ClickMenu - Clicks on an menu item,link
ClickMenuImage - Clicks on an menu item that is a image.
Click a Menu or Sub Menu Item
ClickNthImage click on the Nth Image
ClickNthLink - click on the Nth link
ClickOuterLink - clicks  on a link using outertext
ClickPageLink - click on the page link
ClickIndexLink
printLinkIndex
GetTextBox - get tectbox value
SettextBox  - Sets texbox value
GetNames - get the names of the form elements
GetListbox - gets selected listbox item
SetlistBox - sets selected listbox item
GetRadioButton - Gets Radio button status
SetRadioButton  - Sets Radio button
GetRadioButtonSet - same as above
getTableData - returns the text in table
showAllTableText - finds all text(indexed)in table on the web page
showTableLinkText - finds the link text
dialogcontroller - manipulates modal dialogs
ExecuteJS - executes a JavaScript Function on the page

and much much more !!!