サーバーの監視をするスクリプト
サーバーの監視スクリプトを作成するには、サーバーの様々なリソース(CPU、メモリ、ディスク使用量など)やサービス(HTTPサーバーやデータベースなど)の状態を定期的に取得し、必要に応じてアラートを発信する機能を組み込むことが一般的です。以下は、基本的な監視スクリプトの例です。
この例では、Pythonを使用していますが、他の言語でも同様のコンセプトを適用できます。スクリプト内で使用するモジュールやツールには、Prometheus、Grafana、Nagios、Zabbixなどの監視ツールがありますが、ここではシンプルな例を示します。
python
import paramiko import subprocess import smtplib from email.mime.text import MIMEText import time def send_email(subject, body): # メール送信のための設定 sender_email = "your_email@example.com" receiver_email = "recipient_email@example.com" smtp_server = "smtp.example.com" smtp_port = 587 smtp_username = "your_smtp_username" smtp_password = "your_smtp_password" # メールの作成 message = MIMEText(body) message["Subject"] = subject message["From"] = sender_email message["To"] = receiver_email # メールの送信 with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(smtp_username, smtp_password) server.sendmail(sender_email, receiver_email, message.as_string()) def check_remote_resource(hostname, username, private_key_path): try: # ローカルの秘密鍵のパスを指定 private_key = paramiko.RSAKey(filename=private_key_path) # SSHクライアントの作成 ssh = paramiko.SSHClient() # ホストキーの自動追加を許可 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 公開鍵認証で接続 ssh.connect(hostname, username=username, pkey=private_key) # リモートマシン上で実行するコマンドを指定 commands = ["free -m", "df -h", "systemctl is-active nginx"] results = [] for command in commands: # コマンドの実行 stdin, stdout, stderr = ssh.exec_command(command) result = stdout.read().decode("utf-8") results.append(result) return results except Exception as e: print(f"Error during SSH connection or command execution: {e}") return None finally: # SSHセッションの終了 ssh.close() if __name__ == "__main__": remote_hostname = "your_server_ip" remote_username = "your_username" private_key_path = "/path/to/your/private/key" while True: # リモートサーバーのリソースを確認 results = check_remote_resource(remote_hostname, remote_username, private_key_path) if results: # 結果の表示 for result in results: print(result) # 例: メモリの空き容量が一定以下の場合にメールで通知 free_memory = int(results[0].split()[8]) # freeコマンドの結果から空きメモリを取得 if free_memory < 1000: # 仮の閾値 send_email("Low Memory Alert", f"Free Memory is low: {free_memory} MB") # 60秒ごとに監視 time.sleep(60)
このスクリプトでは、リモートサーバーのメモリ使用量、ディスク使用量、Nginxサービスの状態を取得して表示し、メモリが一定以下になった場合にメールで通知する例を示しています。実際の利用状況に合わせて閾値や監視対象を変更してください。

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