LoginSignup
16
19

More than 5 years have passed since last update.

PythonからリモートPCの色んな情報を抜いてみた by WMI Library

Last updated at Posted at 2017-05-29

はじめに

数百台あるクライアントPCから各種情報を採集する必要があり、Pythonコードを書いて楽をしたので、その時のメモです。
ちなみにADドメイン環境下を想定しています。

前準備

リモートPC

リモートPCで以下のサービスが実行されているか確認する。
もし実行されていないようであれば、グループポリシーなり力業なりで自動起動するように設定する。

  • Remote Procedure Call(RPC)
  • Windows Management Instrumentation

ADグループポリシー設定

以下のページを参考に、グループポリシーを利用してリモートPCのRPC接続を有効化する。
Windowsファイアウォールのリモート管理を有効にする

グループポリシーを直ぐに反映するには、リモートPC側で強制適用する。

cmd.exe
gpupdate /force

Python環境設定

リモート接続する側(Pythonコード実行環境)で、WMIに必要なモジュールをインストールする。

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クライアントの初期化(ローカルPCへ接続する場合)
#conn = wmi.WMI()
## WMIクライアントの初期化(リモートPCへ接続する場合)
conn = wmi.WMI(NODE, user=USER, password=PASS)

# コンピュータ名の取得
# Win32_OperatingSystem => http://www.wmifun.net/library/win32_operatingsystem.html
obj = conn.Win32_OperatingSystem()[0]
print("Hostname: %s" % obj.CSName)

## Cドライブの空き容量チェック(GB単位、小数点下2桁まで)
## Win32_LogicalDisk クラス => 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))

## 現在ログオン中のユーザーアカウント確認
## Win32_ComputerSystem クラス => http://www.wmifun.net/library/win32_computersystem.html
obj = conn.Win32_ComputerSystem()[0]
print("LogonUser: %s" % obj.UserName)

## PCの製造番号(シリアルNO)確認
## Win32_ComputerSystemProduct クラス => http://www.wmifun.net/library/win32_computersystemproduct.html
obj = conn.Win32_ComputerSystemProduct()[0]
print("SerialNo: %s" % obj.IdentifyingNumber)

## コマンド実行
## Win32_Process クラス => http://www.wmifun.net/library/win32_process.html
CMD = "notepad.exe"
CUD = None
## フルパスの場合、セパレータ文字(\)を更にエスケープ
#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

実行結果

% python sample.py
Hostname: HOST-1
FreeSpace: 18.53
LogonUser: MYDOMAIN\user001
SerialNo: JPA12345LF
ProcessId: 3784

その他

  • リモートPCのアプリケーションを実行する場合、対話型アプリケーション(Notepad等)は画面が表示されない。これはセキュリティ上の仕様とのこと。(>= Windows XP SP3 ?)
  • WMIを利用するには、ローカル管理者アカウント、またはドメイン管理者アカウントによる接続が必要。(= Access Denied)

参考

wmi Tutorial
WMI Library

16
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
19