paramiko操作服务器查询cpu,内存,磁盘使用情况

# -*- coding: utf-8 -*-
import paramiko


# @Singleton
class SSHLinuxClient(object):
def __init__(self, hostname, port, username, password, key_filename):
self.hostname = hostname
self.port = port
self.username = username
self.password = password
self.key_filename = key_filename
self.connections = list()

def __enter__(self):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(hostname=self.hostname, port=self.port, username=self.username, key_filename=self.key_filename)
self.connections.append(client)
return client

def __exit__(self, exc_ty, exc_val, tb):
self.connections.pop().close()


class ServiceClient:

def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(ServiceClient, cls).__new__(cls)
# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
cls._instance.ssh_client = SSHLinuxClient(hostname=DefaultConfig.SSH_HOST, port=DefaultConfig.SSH_PORT,
username=DefaultConfig.SSH_USERNAME,
password=DefaultConfig.SSH_PASSWORD,
key_filename=DefaultConfig.SSH_FILENAME_PATH)
return cls._instance

# 内存使用率
def service_ram_rate(self):
with self.ssh_client as ssh:
ram = ssh_command(ssh, SSH_COMMAND['ram'])
service_ram = ram.split('\n')
# ram_use = int(service_ram[2])
# ram_all = int(service_ram[1])
# ram_rate = int(ram_use / ram_all * 100)
for line in service_ram:
if line.startswith('MemTotal:'):
mem_total = int(line.split()[1])
elif line.startswith('MemFree:'):
mem_free = int(line.split()[1])
elif line.startswith('Buffers:'):
mem_buffer = int(line.split()[1])
elif line.startswith('Cached:'):
mem_cache = int(line.split()[1])
elif line.startswith('SwapTotal:'):
vmem_total = int(line.split()[1])
elif line.startswith('SwapFree:'):
vmem_free = int(line.split()[1])
else:
continue
physical_percent = self.usage_percent(mem_total - (mem_free + mem_buffer + mem_cache), mem_total)
virtual_percent = 0
if vmem_total > 0:
virtual_percent = self.usage_percent((vmem_total - vmem_free), vmem_total)
return mem_total, physical_percent, virtual_percent
# return ram_rate

@staticmethod
def usage_percent(use, total):
try:
ret = (float(use) / total) * 100
except ZeroDivisionError:
raise Exception("ERROR - zero division error")
return ret

# cpu使用率
def service_cpu_rate(self):
last_work_time = 0
last_idle_time = 0
with self.ssh_client as ssh:
cpu = ssh_command(ssh, SSH_COMMAND['cpu'])
service_cpu = cpu.split('\n')
line = ''
for cpu in service_cpu:
if 'cpu' in cpu:
line = cpu
break
# line = ''
# f = open('1.txt', 'r')
# while not "cpu " in line: line = f.readline()
spl = line.split(" ")
work_time = int(spl[2]) + int(spl[3]) + int(spl[4])
idle_time = int(spl[5])
d_work_time = (work_time - last_work_time)
d_idle_time = (idle_time - last_idle_time)
rate = float(d_work_time) / (d_idle_time + d_work_time)
last_work_time = work_time
if last_work_time == 0:
return 0
return rate * 100

# 返回总 和 使用率
def service_disk_rate(self):
disk_size = 0
disk_size_use = 0
with self.ssh_client as ssh:
disk = ssh_command(ssh, SSH_COMMAND['disk'])
service_disk_list = disk.split('\n')[1:]
service_disk_list = [disk for disk in filter(lambda x: x != '', service_disk_list)]
for service_disk in service_disk_list:
disk_list = [disk for disk in filter(lambda x: x != '', service_disk.split(' '))]
disk_size += int(disk_list[1])
disk_size_use += int(disk_list[2])

return disk_size, disk_size_use / disk_size

# cpu配置及数量
def service_cpu_count(self):
cpu = str()
with self.ssh_client as ssh:
cpu_config_list = ssh_command(ssh, SSH_COMMAND['cpu_config']).split('\n')
for cpu_config in cpu_config_list:
if 'model name' in cpu_config:
model_name = cpu_config.split(' : ')[1]
cpu += model_name
elif 'cpu cores' in cpu_config:
cpu_cores = cpu_config.split(' : ')[1]
cpu += ' * ' + cpu_cores
return cpu

# ssh相关命令
SSH_COMMAND = {
'cpu': 'cat /proc/stat',
'ram': 'cat /proc/meminfo',
'disk': 'df',
'cpu_config': 'cat /proc/cpuinfo',
}
posted @ 2022-05-30 17:55  wyz_1  阅读(130)  评论(0编辑  收藏  举报