How do I get my pc's windows Workgroup name in python

691 Views Asked by At

I'm trying to find my workGroup name in python, does anybody know a function for that?

2

There are 2 best solutions below

0
On
import wmi
wmi_os = wmi.Win32_ComputerSystem()[0]
print(wmi_os.Workgroup)

You also can go further and take a look at print(wmi_os.__dict__['properties'].keys())

dict_keys(['AdminPasswordStatus', 'AutomaticManagedPagefile', 'AutomaticResetBootOption', 'AutomaticResetCapability', 'BootOptionOnLimit', 'BootOptionOnWatchDog', 'BootROMSupported', 'BootStatus', 'BootupState', 'Caption', 'ChassisBootupState', 'ChassisSKUNumber', 'CreationClassName', 'CurrentTimeZone', 'DaylightInEffect', 'Description', 'DNSHostName', 'Domain', 'DomainRole', 'EnableDaylightSavingsTime', 'FrontPanelResetStatus', 'HypervisorPresent', 'InfraredSupported', 'InitialLoadInfo', 'InstallDate', 'KeyboardPasswordStatus', 'LastLoadInfo', 'Manufacturer', 'Model', 'Name', 'NameFormat', 'NetworkServerModeEnabled', 'NumberOfLogicalProcessors', 'NumberOfProcessors', 'OEMLogoBitmap', 'OEMStringArray', 'PartOfDomain', 'PauseAfterReset', 'PCSystemType', 'PCSystemTypeEx', 'PowerManagementCapabilities', 'PowerManagementSupported', 'PowerOnPasswordStatus', 'PowerState', 'PowerSupplyState', 'PrimaryOwnerContact', 'PrimaryOwnerName', 'ResetCapability', 'ResetCount', 'ResetLimit', 'Roles', 'Status', 'SupportContactDescription', 'SystemFamily', 'SystemSKUNumber', 'SystemStartupDelay', 'SystemStartupOptions', 'SystemStartupSetting', 'SystemType', 'ThermalState', 'TotalPhysicalMemory', 'UserName', 'WakeUpType', 'Workgroup'])

Some of them might be useful for you

0
On

I was looking for the exact thing and I could not find a direct way through Python. Instead I had to use subprocess to run a PowerShell command:

import subprocess

domain = subprocess.run(["powershell.exe", "(Get-CimInstance Win32_ComputerSystem).Domain"], stdout=subprocess.PIPE, text=True)
domain = domain.stdout.strip()

print(domain)

You can also just make it a one-liner by appending stdout.strip() directly to subprocess():

import subprocess

domain = subprocess.run(["powershell.exe", "(Get-CimInstance Win32_ComputerSystem).Domain"], stdout=subprocess.PIPE, text=True).stdout.strip()

print(domain)

Result:

"mydomain.com"    # domain-joined computer
# OR
"workgroup"    # workgroup name

I've included the string method strip() to remove the trailing \n characters that STDOUT produces.

The PowerShell command (Get-CimInstance Win32_ComputerSystem).Domain retrieves either the domain name that the computer is joined to, or just the workgroup name if it's not joined to a domain.

NOTE:
I saw older suggestions on StackOverflow using the PowerShell command Get-WmiObject, which only works with PowerShell 5.1. Microsoft recommends using the newer Get-CimInstance, which works with PowerShell 5.1 and newer (ie: PowerShell Core)