[python-win32] Domain iteration (for the archive and general knowledge).

Sean null-python-win32 at tinfoilhat.ca
Wed Aug 27 18:46:34 EDT 2003


The following code gets around the problem where your network is segmented
on different VLANs and broadcasts are not being propogated.  It uses the
'ADsNameSpaces' to enumerate all the items in the "Server Manager"
application under NT4.

The caveat here is that this solution is slow on large numbers of
machines because I've not found a ping module which works with python
2.2+ and use popen instead.  The is_responding() function is the problem
for this reason.

Machines need to be checked if they are responding (especially if you want
to use WMI features as it takes FOREVER for the WMI connect to timeout)
every invocation otherwise I'd pickle the domains list between program
calls.

The code posted below is just cut/pasted and modified from a class I've
written and only contains enough code to determine what machines are in
the NT domain and which are online.  The result of enumerate() is a list of
names for machines that are both in the domain and responding.  You can
iterate through this list using WMI stuff and lots of fun (and time
saving) will result.

Any ideas, suggestions or comments?
Any ideas how to make it faster?

<tt>

    def enumerate():
	# change MY_NT_DOMAIN to your NT domain name.
        adsi = win32com.client.Dispatch("ADsNameSpaces")
        nt = adsi.GetObject("","WinNT:")
        result = nt.OpenDSObject("WinNT://MY_NT_DOMAIN","","",0)
        result.Filter = ["computer"] # what other items can be 'filtered'?
        domain = []
        for machine in result:
            domain.append(machine.Name)
    	return domain

    # made global so the expressions are not 'compliled' every call.
    # using the regex library as the output of ping would be multiple lines
    not_found = re.compile("Unknown host",re.M)
    not_responding = re.compile("Request timed out.",re.M)

    def is_responding(name):
        cmd = "ping -n 1 %s" % name # only need one ping request.
        output = os.popen(cmd,"r")
        response = output.read()
        value = 0
	# It could be useful to differentiate if a machine name doesn't
        # resolve or it is not responding to pings.
        if not_found.search(response):
            value = 1
        elif not_responding.search(response):
            value = 2
        else:
            value = 0
        return value

	# Main loop.
	for machine in enumerate():
		if is_responding() != 0:
			print machine," is not responding."
		else:
			print machine," is responding.
</tt>
-- 
Sean





More information about the Python-win32 mailing list