Paramiko allows collecting server metrics remotely. This tutorial shows how to gather system information. This is very useful for monitoring.
Establishing an SSH Connection
First, establish a secure SSH connection to the server. This is the foundation for remote commands. This requires valid credentials.
import paramiko
def connect_to_server(hostname, username, password):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username, password)
return ssh
except Exception as e:
print(f"Connection error: {e}")
return None
ssh = connect_to_server("your_hostname", "your_username", "your_password")
Executing Commands Remotely
Use exec_command()
to run commands on the server. This retrieves the output of the commands. This is how we get metrics.
import paramiko
def execute_command(ssh, command):
try:
stdin, stdout, stderr = ssh.exec_command(command)
output = stdout.read().decode().strip()
return output
except Exception as e:
print(f"Command execution error: {e}")
return None
if ssh:
uptime = execute_command(ssh, "uptime")
print(f"Server Uptime: {uptime}")
Collecting CPU Usage
Use commands like top or mpstat to get CPU usage. Parse the output to extract relevant metrics. This provides insights into system load.
import paramiko
import re
if ssh:
cpu_info = execute_command(ssh, "mpstat 1 1 | tail -1") # Get last line of mpstat
if cpu_info:
cpu_idle = float(cpu_info.split()[-1])
cpu_usage = 100 - cpu_idle
print(f"CPU Usage: {cpu_usage:.2f}%")
Collecting Memory Usage
Use the free -h command to get memory information. Parse the output to extract memory usage. This helps monitor memory resources.
import paramiko
if ssh:
mem_info = execute_command(ssh, "free -h | grep Mem")
if mem_info:
mem_parts = mem_info.split()
total_mem = mem_parts[1]
used_mem = mem_parts[2]
print(f"Total Memory: {total_mem}, Used Memory: {used_mem}")
Collecting Disk Space
Use the df -h command to get disk space information. Parse the output to extract disk usage. This helps monitor available storage.
import paramiko
if ssh:
disk_info = execute_command(ssh, "df -h | grep /dev/vda1") # Change /dev/vda1 to your disk
if disk_info:
disk_parts = disk_info.split()
used_space = disk_parts[2]
available_space = disk_parts[3]
print(f"Used Space: {used_space}, Available Space: {available_space}")
if ssh:
ssh.close()