List the machines in a domain

Introduction

The requirement: given a domain name, to list the machines within it.

This is a little tricky, because how do you define "the machines within a domain"? It's a little easier now, since WinNT+ machines are always domain workstations or servers, rather than simply clients. The code illustrates the use of the WinNT provider, even where Active Directory is not running.

#
# From a post to python-win32 by D.W.Harks
# http://mail.python.org/pipermail/python-win32/2003-July/001179.html
#
from __future__ import generators
import os, sys
import socket
import win32com.client
import win32net

def machines_in_domain (domain_name):
  adsi = win32com.client.Dispatch ("ADsNameSpaces")
  nt = adsi.GetObject ("","WinNT:")
  result = nt.OpenDSObject ("WinNT://%s" % domain_name, "", "", 0)
  result.Filter = ["computer"]
  for machine in result:
    yield machine.Name

domain_controller = win32net.NetGetDCName (None, None)
domain_name = win32net.NetUserModalsGet (domain_controller, 2)['domain_name']
print "Listing machines in", domain_name
for machine in machines_in_domain (domain_name):
  print machine