python 服务器数据采集

01 agent模式

在要采集的服务器上采集数据,然后上报到指定的服务器

subprocess

通过子进程来执行外部指令,并通过input/output/error管道,获取子进程的执行的返回信息

subprocess.call(['df','-hT'], shell=False)

​ 执行命令,并返回执行状态,其中shell参数为False时,命令需要通过列表的方式传入,当shell为True时,可直接传入命令

subprocess.getoutput('df')

​ 结果是执行命令后的值,

​ 可以执行命令,然后自己去切割处理数据

psutil

安装

pip3 install psutil

​ 如果提示没权限,加上sudo

cpu

import psutil

# cpu个数
psutil.cpu_count() # logical默认是True,逻辑个数
psutil.cpu_count(logical=False) # 物理个数

# cpu使用率
psutil.cpu_percent(interval=0.5, percpu=False) 
"""
interval 阻塞时间,默认不阻塞
percpu 显示所有cpu使用率,默认不显示
"""

内存

import psutil

# 内存使用率
psutil.virtual_memory() 
"""
结果分析(元组):
total 物理内存总数
available 可用物理内存
used 已使用物理内存
percent 已使用百分比
"""

psutil.swap_memory() 
"""
结果分析(元组):
total 总交换内存(以字节为单位
used 使用的交换内存(以字节为单位、free:可用字节交换内存
percent 使用的百分比
sin 系统已从磁盘交换的字节数(累积、sout:系统已从磁盘换出的字节数(累积)
"""

硬盘

import psutil

# 硬盘使用信息
psutil.disk_usage(path) 

"""
path 要获取的路径

结果分析(元组):
total 总的
used 已使用的
free 剩余的
percent 使用百分比
"""

# 获取硬盘挂载信息
psutil.disk_partitions(all=False) 
"""
all 是否获取虚拟硬盘(非物理硬盘信息),默认是False不获取
"""

网卡

# 网卡信息
psutil.net_io_counters(pernic=False)
"""
pernic 是否获取网卡的全部信息,默认是False不获取

结果分析(元组):
bytes_sent 发送字节数
bytes_recv 接受字节数
packets_sent 发送数据包
packets_recv 接收数据包
errin 错误包接收包
errout 错误出栈包 
dropin 丢弃入栈包 
dropout 丢弃出栈包 
"""

其他

import psutil

# 开机时间(时间戳)
psutil.boot_time()
# 转化为格式化
datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")

02 SSH模式

在固定的服务器上,远程连要采集的服务器,采集数据

import paramiko

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname="ip", port="端口", username="用户名", password="密码")
# 执行命令
stdin, stdout, stderr = ssh.exec_command("linux命令")
# 获取命令结果
result = stdout.read()
# 关闭连接
ssh.close()

线程池并发采集

from concurrent.futures import ThreadPoolExecutor
    p = ThreadPoolExecutor(10)
        p.submit("采集的方法")

总结

​ 01 优点采集速度快,效率高,缺点每个节点都要装agent

​ 02 优点只需要在know_hosts文件中加需要采集的节点信息,方便部署,缺点采集速度慢,相对没那么及时

posted @ 2020-08-19 17:30  tianzhh_lynn  阅读(942)  评论(0编辑  收藏  举报