TypeError: cannot unpack non-iterable HTTPBasicAuth object
winrmのHTTPBasicAuthは誤りでした。Windowsリモート管理(WinRM)では、NTLM認証を使用するのが一般的です。
以下は修正されたPythonスクリプトです。
python
import requests
from requests.auth import HTTPNtlmAuth
import winrm
import json
def run_command(hostname, username, password, command):
session = winrm.Session(
hostname,
auth=HTTPNtlmAuth(username, password),
server_cert_validation='ignore',
)
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, password):
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, password, 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マシンのユーザー名"
remote_password = "リモートWindowsマシンのパスワード"
get_system_info(remote_hostname, remote_username, remote_password)
これにより、NTLM認証が正しく行われるように修正され、エラーが解消されるはずです。お試しください。

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