使用 Ansible 统计服务器资源利用率:
3 条 shell 脚本实现统计:
CPU 利用率统计
top
-bn1 |
grep
load |
awk
'{printf "CPU Load: %.2f
", $(NF-2)}'
内存利用率统计:
free
-m |
awk
'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)
", $3,$2,$3*100/$2 }'
磁盘利用率统计(列出每块磁盘利用率):
df
-h -t ext2 -t ext4 |
grep
-vE
'^Filesystem|tmpfs|cdrom'
|
awk
'{ print "Disk Usage:"" " $1 " " $3"/"$2" ""("$5")"}'
--- - name: test hosts: localhost tasks: - name: disk_detail shell: df -h -t ext2 -t ext4 | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print "Disk Usage:"" " $1 " " $3"/"$2" ""("$5")"}' register: disk_detail - name: cpu_detail shell: top -bn1 | grep load | awk '{printf "CPU Load %.2f ", $(NF-2)}' register: cpu_detail - name: memory_detail shell: free -m | awk 'NR==2{printf "Memory Usage %s/%sMB (%.2f%%) ", $3,$2,$3*100/$2 }' register: memory_detail - name: resultcopy:content: ><p>{{ansible_facts.default_ipv4.address}}</p><p>{{disk_detail.stdout_lines}}</p><p>{{cpu_detail.stdout_lines}}</p><p>{{memory_detail.stdout_lines}}</p><p>-------------------------------------</p>dest: /root/flask/static/content.html
PLAYBOOK 文件编写 将资源利用率输出到 falsk static文件夹内
from flask import Flask import os from flask import make_response from flask import render_template app = Flask(__name__) @app.route('/') def index(): APP_ROOT = os.path.dirname(os.path.abspath(__file__)) # refers to application_top APP_STATIC = os.path.join(APP_ROOT, 'static') with open(os.path.join(APP_STATIC, 'content.html')) as f:response = f.read() return response if __name__ == '__main__': app.run(debug=True,host='10.130.130.80',port=5003)
简单的flask小项目 可供访问