cpu stats in linux code example

Example 1: linux check cpu usage

lscpu

# Or
cat /proc/cpuinfo

Example 2: check CPU usage on ssh server

import numpy as np
from tqdm import tqdm
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname, username=usr, password=psswrd, port=22)

print('Checking CPU usage on %s...' %hostname)
cpu_usage=[]
for i in tqdm(range(0,60)):
    cmd ="mpstat 1 2 | awk 'END{print 100-$NF}'"
    stdin, stdout, stderr = ssh.exec_command(cmd)
    
    for line in stdout.readlines():
        cpu_usage.append(np.float(line[:-2]))
        
ssh.close()