command_to_run = “ここに実行したいPowerShellコマンドを指定” CPU、メモリの利用率がほしい
CPUおよびメモリの利用率を取得するためには、リモートのWindowsマシンで実行されるPowerShellスクリプトを使って情報を収集し、その情報をPythonスクリプトで取得する必要があります。以下は、それを行う一般的なスクリプトの例です。
PowerShellスクリプト (get_system_info.ps1):
powershell
$cpuUsage = Get-Counter 'Processor(_Total)% Processor Time' | Select-Object -ExpandProperty CounterSamples | Select-Object -ExpandProperty CookedValue $memoryUsage = Get-Counter 'MemoryAvailable MBytes' | Select-Object -ExpandProperty CounterSamples | Select-Object -ExpandProperty CookedValue # Output JSON @" { "cpuUsage": $cpuUsage, "memoryUsage": $memoryUsage } "@
Pythonスクリプト:
python
import requests from requests.auth import HTTPBasicAuth import winrm import json def run_command(hostname, username, private_key_path, command): session = winrm.Session( hostname, auth=HTTPBasicAuth(username, ''), server_cert_validation='ignore', transport='ntlm', keyfile=private_key_path, certfile=private_key_path ) 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) return result.std_out.decode('utf-8') def get_system_info(hostname, username, private_key_path): command_to_run = ''' $scriptPath = "C:\path\to\get_system_info.ps1" $scriptContent = Get-Content -Raw $scriptPath Invoke-Expression -Command $scriptContent ''' result = run_command(hostname, username, private_key_path, command_to_run) try: json_data = json.loads(result) cpu_usage = json_data.get('cpuUsage', 'N/A') memory_usage = json_data.get('memoryUsage', 'N/A') print(f"CPU Usage: {cpu_usage}%") print(f"Memory Usage: {memory_usage} MB") except json.JSONDecodeError as e: print(f"Error decoding JSON: {e}") if __name__ == "__main__": remote_hostname = "リモートWindowsマシンのIPアドレスまたはホスト名" remote_username = "リモートWindowsマシンのユーザー名" private_key_path = "生成したSSH秘密鍵のパス" get_system_info(remote_hostname, remote_username, private_key_path)
この例では、PowerShellスクリプト (get_system_info.ps1) でCPUおよびメモリの利用率をJSON形式で出力し、Pythonスクリプトでその情報を受け取って表示しています。お使いの環境に合わせてファイルパスやPowerShellスクリプトの内容を適切に設定してください。

ディスカッション
コメント一覧
まだ、コメントがありません