Shell script to view the basic information of the current server cluster in batches

Shell script to view the basic information of the current server cluster in batches

1. Use scripts to distribute public keys in batches to Ansible managed servers

#分发秘钥脚本一:
#!/bin/bash
for ip in `cat /opt/server/ip.txt`
do
sshpass -p'密码' ssh-copy-id -i /root/.ssh/id_dsa.pub $ip -o StrictHostKeyChecking=no 1>/dev/null 2>/var/log/ssh.log
if [ $? -eq 0 ]
then
   echo "主机 $ip 分发秘钥成功"
else
   echo "主机 $ip 分发秘钥失败"
fi
done

2. Add the controlled host to the ansible host list file

在/etc/ansible/hosts中最后一行添加主机ip
[node]
192.168.xx.xxx
192.168.xx.xxx

3. Test whether the control is successful

ansible all --list #查看被控节点的主机

4. Write a playbook (file ending with .yml) under /etc/ansible

vim /etc/ansible/mount.yml
- hosts: node
  user: 用户名
  tasks:
  - name: 复制脚本到被控节点
    copy: src=/opt/脚本.sh dest=/root
  - name: 执行脚本
    shell: bash /root/脚本.sh

5. Check the syntax of the playbook and run

ansible-playbook  mount.yml --check #语法没有问题的话直接运行
ansible-playbook  mount.yml

6. Write scripts

#!/bin/bash
for ip in `cat /opt/server/ip.txt`
do
#内存使用情况
a=`ssh root@$ip free -h|awk 'NR==2 {print $2}'`
b=`ssh root@$ip free -h|awk 'NR==2 {print $3}'`
c=`ssh root@$ip free -h|awk 'NR==2 {print $4}'`
#交换分区使用情况
a1=`ssh root@$ip free -h|grep Swap|awk '{print $2}'`
b1=`ssh root@$ip free -h|grep Swap|awk '{print $3}'`
c1=`ssh root@$ip free -h|grep Swap|awk '{print $4}'`
#硬盘使用情况
d=`ssh root@$ip df -h / |awk 'NR==2{print $2}'`
e=`ssh root@$ip df -h / |awk 'NR==2{print $4}'`
#CPU使用情况
cpu_a=`ssh root@$ip cat /proc/cpuinfo|awk -F: 'NR==5 {print $2}'`
cpu_b=`ssh root@$ip "grep -c 'model name' /proc/cpuinfo"`
cpu_c=`ssh root@$ip top -b -n 1 | grep Cpu|awk -F"," '{print $4}'|cut -f 1 -d "."`
cpu_d=`ssh root@$ip uptime |awk -F"," '{print $3,$4,$5,$6}'`
to=`date -d "0 day" +%Y年%m月%d日`
hostname=`ssh root@$ip hostname`
ping -c2 $ip >/dev/null 2>&1
if [ $? -eq 0 ]
then
echo -e "\033[32m############### 主机$ip使用情况 ###############\033[0m"
        echo "主机名称:$hostname"
        echo "当前时间:$to"
        echo "主机可以ping通"
        echo "主机IP:$ip"
        echo "内存使用情况:"
        echo "总内存:$a  使用内存:$b  剩余内存:$c"
        echo "交换分区使用情况:"
        echo "总内存:$a1 使用内存:$b1  剩余内存:$c1"
        echo "系统盘总容量:$d  系统盘剩余容量:$e"
        echo "CPU型号名称:$cpu_a"
        echo "CPU总核心数:$cpu_b"
        echo "CPU空闲比为:$cpu_c%"
        echo "CPU负载情况:$cpu_d"
echo -e "\033[32m#####################################################\033[0m"
else
        echo "主机 $ip ping不通"
fi
done

summary

此脚本需要先到管理机的/opt/server/ip.txt文件中写入要批量查看的服务器ip地址
再使用循环语句批量分发密钥再进行查看服务器当前的使用情况

insert image description here

Guess you like

Origin blog.csdn.net/HYXRX/article/details/115550379