WindowsでリモートマシンのメモリやCPUの利用率を取得

2024年6月18日

はい、Windowsでも同様の手法でリモートマシンのメモリやCPUの利用率を取得することができます。ただし、WindowsではSSHではなく、通常はWinRM(Windows Remote Management)や他のリモート管理ツールを使用することが一般的です。

以下は、psutilpywinrm ライブラリを使用して、Windowsマシンへのリモート接続を行い、メモリの利用率を取得する例です。

まず、pywinrm ライブラリをインストールします。

bash
pip install pywinrm

次に、以下のPythonスクリプトを使用して、Windowsマシンのメモリ利用率を取得します。

python
import psutil
import winrm

def get_remote_memory_usage(hostname, username, password):
    session = winrm.Session(
        hostname, 
        auth=(username, password),
        server_cert_validation='ignore'  # SSL証明書の検証を無効にする(テスト用)
    )

    # ここでリモートマシン上で実行するコマンドを指定
    command = "Get-Counter '\Memory\Available MBytes'"

    encoded_ps = f"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('{command}'))"
    ps_script = f"$command = {encoded_ps}; Invoke-Expression $command"

    encoded_ps_script = ps_script.encode('utf_16_le').decode('latin_1')

    result = session.run_ps(encoded_ps_script)

    # 結果からメモリの使用状況を取り出す処理を追加することができます
    # 結果は result.std_out に格納されています

    print(f"Remote Memory Usage:n{result.std_out.decode('utf-8')}")

if __name__ == "__main__":
    remote_hostname = "リモートWindowsマシンのIPアドレスまたはホスト名"
    remote_username = "リモートWindowsマシンのユーザー名"
    remote_password = "リモートWindowsマシンのパスワード"

    get_remote_memory_usage(remote_hostname, remote_username, remote_password)

この例では、winrm ライブラリを使用してWindowsマシンに対してリモート接続し、PowerShellコマンドを実行してメモリの使用状況を取得しています。セキュリティの観点から、実際の環境で使用する際には適切なセキュリティ対策を講じてください。

未分類

Posted by ぼっち