shell 编程实战收集服务器信息

基于shell脚本实现自动化服务器硬件信息的收集,并将收集的内容存放在数据库,能更快、更高效地实现对服务器资产信息的管理,shell脚本实现服务器信息自动收集,思路如下:
创建数据库和表存储服务器信息;
基于shell四剑客awk、find、sed、grep获取服务器信息;
将获取的信息写成SQL语句;
定期对SQL数据进行备份;
将脚本加入crontab实现自动备份。
创建数据库表,创建SQL语句:
CREATE TABLEaudit_system (
idint(11) NOT NULL AUTO_INCREMENT,
ip_infovarchar(50) NOT NULL,
serv_infovarchar(50) NOT NULL,
cpu_infovarchar(50) NOT NULL,
disk_infovarchar(50) NOT NULL,
mem_infovarchar(50) NOT NULL,
load_infovarchar(50) NOT NULL,
mark_infovarchar(50) NOT NULL,
PRIMARYKEY (id),
UNIQUEKEY ip_info (ip_info),
UNIQUEKEY ip_info_2 (ip_info)
);
shell 脚本实现服务器信息自动收集:
#!/bin/bash
#Auto get system info
#By author tang.com2018
#Define Path variables
echo -e "\033[32m\033[1m"
cat << EOF
+++++++++++++++++++++++++++++++++++++++++++++
+++++++++Welcome to usesystem Collet++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++
EOF
ip_info=`ifconfig |grep "broadcast" |tail -1 |awk '{print $2}'`
cpu_info1=`cat /proc/cpuinfo |grep 'model name'|tail -1|awk -F: '{print $2}'|sed 's/^ //g'|awk '{print $1,$2,$4,$NF}'`
cpu_info2=`cat /proc/cpuinfo |grep "physical id"|sort|uniq -c|wc -l`
serv_info=`hostname|tail -1`
disk_info=`fdisk -l|grep "Disk"|head -1|grep -v "identifier"|awk '{print $2,$3,$4}' |sed 's/,//g'`
mem_info=`free -m|grep 'Mem'|awk '{print "Total",$1,$2"M"}'`
load_info=`uptime |awk '{print "Current Load: "$(NF-2)}'|sed 's/\,//g'`
mark_info=HANZHOU_IDC
echo -e"\033[32m--------------------------------------------------------------------------\033[1m"
echo IPADDR: ${ip_info}
echo HOSTNAME: ${serv_info}
echo CPU_INFO: ${cpu_info1} X ${cpu_info2}
echo DISK_INFO: ${disk_info}
echo MEM_INFO: ${mem_info}
echo LOAD_INFO: ${load_info}
echo MARK_INFO: ${mark_info}
echo -e"\033[32m--------------------------------------------------------------------------\033[0m"
echo -e -n"\033[36mYou wang to write the data to the databases? \033[1m" ; readensure
if ["$ensure" == "yes" -o "$ensure" == "y"-o "$ensure" == "Y" ];then
echo"------------------------------------------------------------------"
echo-e '\033[31mmysql -uroot -p123 -D systeminfo -d ''' "insert intoaudit_systemvalues('','${ip_info}','${serv_info}','${cpu_info1}X${cpu_info2}','${disk_info}','${mem_info}','${load_info}','${mark_info}')"'''\033[0m'
mysql -uroot -p123 -Dsysteminfo -e "insert into audit_systemvalues('','${ip_info}','${serv_info}','${cpu_info1}X${cpu_info2}','${disk_info}','${mem_info}','${load_info}','${mark_info}')"
else 
echo"Please wait,exit......"
exit
fi
手动读取数据库服务器信息命令:
mysql -uroot -p1234 -e'use systeminfo;select * from audit_system;' |sed 's/-//g'|grep -v"id"