Pythonでクラウドのwindowsサーバー(VPS)のメモリー状況を定期的に把握したい。

2024年6月18日

Pythonを使用してクラウド上のWindowsサーバー(VPS)のメモリー状況を定期的に把握するためには、リモートでサーバーにアクセスし、メモリー情報を取得する必要があります。以下は、psutilライブラリを使用してリモートのWindowsサーバーのメモリー情報を取得する簡単なPythonスクリプトの例です。

まず、リモートサーバーにpsutilをインストールする必要があります。リモートサーバー上でPowerShellを使用して、以下のコマンドを実行してください。

powershell
Install-Module -Name psutil -Force -Scope CurrentUser

次に、Pythonスクリプトを作成します。以下のスクリプトは、リモートサーバー上でPythonが実行されていることを前提としています。

python
import psutil
import paramiko
import time

def get_remote_memory_info(hostname, username, password):
    # SSHクライアントの作成
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # SSHでリモートサーバーに接続
        ssh.connect(hostname, username=username, password=password)

        while True:
            # メモリ情報を取得
            memory_info = psutil.virtual_memory()

            # メモリの総容量、使用量、空き容量、使用率を表示
            print(f"Total Memory: {memory_info.total / (1024 ** 2):.2f} MB")
            print(f"Used Memory: {memory_info.used / (1024 ** 2):.2f} MB")
            print(f"Free Memory: {memory_info.free / (1024 ** 2):.2f} MB")
            print(f"Memory Usage Percentage: {memory_info.percent:.2f}%")

            # 30秒ごとにメモリ情報を取得
            time.sleep(30)

    except Exception as e:
        print(f"Error: {e}")

    finally:
        # SSHセッションの終了
        ssh.close()

if __name__ == "__main__":
    remote_hostname = "リモートサーバーのIPアドレス"
    remote_username = "リモートサーバーのユーザー名"
    remote_password = "リモートサーバーのパスワード"

    get_remote_memory_info(remote_hostname, remote_username, remote_password)

このスクリプトでは、paramikoを使用してSSH接続し、psutilを使用してメモリ情報を取得します。30秒ごとにメモリ情報が表示されます。注意点として、パスワードを平文でスクリプト内に保存することはセキュリティ上のリスクです。最も安全な方法はSSHの公開鍵認証を使用することです。

未分類

Posted by ぼっち