It was necessary to collect various information from hundreds of client PCs, and I enjoyed writing Python code, so this is a memo at that time. By the way, it is assumed to be in an AD domain environment.
Check if the following services are running on the remote PC. If it doesn't seem to be running, set it to start automatically according to Group Policy or force.
Refer to the following page and enable RPC connection of remote PC using Group Policy. Enable remote management of Windows Firewall
To reflect the group policy immediately, enforce it on the remote PC side.
cmd.exe
gpupdate /force
Install the modules required for WMI on the remote connection side (Python code execution environment).
pip install pypiwin32
pip install wmi
sample.py
# coding: utf-8
import wmi
NODE = "host-1.example.local"
USER = "Administrator@MYDOMAIN"
PASS = "P@ssW0rd!"
##WMI client initialization (when connecting to a local PC)
#conn = wmi.WMI()
##WMI client initialization (when connecting to a remote PC)
conn = wmi.WMI(NODE, user=USER, password=PASS)
#Get computer name
# Win32_OperatingSystem => http://www.wmifun.net/library/win32_operatingsystem.html
obj = conn.Win32_OperatingSystem()[0]
print("Hostname: %s" % obj.CSName)
##Check the free space of C drive(GB unit, up to 2 decimal places)
## Win32_LogicalDisk class=> http://www.wmifun.net/library/win32_logicaldisk.html
obj = conn.Win32_LogicalDisk(DeviceID='C:')[0]
free = float(obj.FreeSpace) / 1024 / 1024 / 1024
print('FreeSpace: {:.2f}'.format(free))
##Confirm user account currently logged on
## Win32_ComputerSystem class=> http://www.wmifun.net/library/win32_computersystem.html
obj = conn.Win32_ComputerSystem()[0]
print("LogonUser: %s" % obj.UserName)
##Confirmation of PC serial number (serial number)
## Win32_ComputerSystemProduct class=> http://www.wmifun.net/library/win32_computersystemproduct.html
obj = conn.Win32_ComputerSystemProduct()[0]
print("SerialNo: %s" % obj.IdentifyingNumber)
##Command execution
## Win32_Process class=> http://www.wmifun.net/library/win32_process.html
CMD = "notepad.exe"
CUD = None
##Separator character for full path(\)Further escape
#CMD = "C:\\Users\\Public\\Desktop\\example.exe"
#CUD = "C:\\Users\\Public\\Desktop"
SW_SHOWNORMAL = 1
p_startup = conn.Win32_ProcessStartup.new()
p_startup.ShowWindow = SW_SHOWNORMAL
pid, result = conn.Win32_Process.Create(
CommandLine=CMD,
CurrentDirectory=CUD,
ProcessStartupInformation=p_startup
)
if result == 0:
print "ProcessId: %d" % pid
else:
raise RuntimeError, "Problem creating process: %d" % result
Execution result
% python sample.py
Hostname: HOST-1
FreeSpace: 18.53
LogonUser: MYDOMAIN\user001
SerialNo: JPA12345LF
ProcessId: 3784
--When executing an application on a remote PC, the screen is not displayed for interactive applications (Notepad, etc.). This is a security specification. (> = Windows XP SP3?) --To use WMI, you need to connect with a local administrator account or a domain administrator account. (= Access Denied)
Recommended Posts