Is it possible to return all computers in AD in python
Question: How could I search AD for all computer names?


Answer: It's not great code -- if you're familiar enough with the Windows API I'd
recommend using the `win32con` to do so. However, this is quite functional:

    
    
    import subprocess
    
    splitstring = "\\r\\n"
    bCompList = subprocess.check_output(['dsquery', 'computer', 'domainroot',
                                         '-scope', 'subtree', '-limit', '0'])
    compList = str(bCompList)[2:-5].split(splitstring)
    

The `subprocess` module is used to run external commands; I suggest [reading
up on the
documentation](http://docs.python.org/py3k/library/subprocess.html#module-
subprocess). `subprocess.check_output` captures and returns the output of the
command from stdout. (Note that the command is a list. That's important!)

In this case, we're using `dsquery computer` to query the entire domain
(`'domainroot'`) for all computer objects (`'limit', '0'`). This returns a
binary string -- stored here in `bCompList`.

Since it's a binary string, we'll probably want to convert it to a 'standard'
string format to work with -- that's why we use `str()`. We can use slicing to
trim off the 'junk' characters (the "`b`" which indicated the string was
binary, and the trailing `'\\r\\n'` garbage.) That resultant string then gets
used by `split()` to break it up into a list.

Incidentally, if you want to trim off the quotation marks `dsquery computer`
places around each computer object, change the slicing to `[3:-6]` and change
`splitstring = "\\r\\n"` to `splitstring = "\"\\r\\n\""`.

There are two significant caveats to this code, however:

  * It must be run on a computer with the Windows "AD DS Snap-Ins and Command-Line Tools" feature installed (at least, that's what they're called in Windows Server 2008 R2.)
  * You need to be logged in as an AD user with appropriate privileges. (Alternatively, you could include `'-u', username, '-p', password` in the command argument list, replacing `username` and `password` with the appropriate credentials.)

