以centos7为例:
此功能针对Linux集群,通过其中一台命令控制多台Linux系统。
实现方法command.sh 脚本
#!/bin/bash
if [ -z $1 ]; then
echo "Usage: $0 command"
exit 1
fi
HOST_LIST_FILE=host_list.txt
COMMAND=$@
for IP in $(awk '/^[^#]/{print $1}' $HOST_LIST_FILE); do
USER=$(awk -v I=$IP 'I==$1{print $2}' $HOST_LIST_FILE)
PASS=$(awk -v I=$IP 'I==$1{print $3}' $HOST_LIST_FILE)
PORT=$(awk -v I=$IP 'I==$1{print $4}' $HOST_LIST_FILE)
echo "-------- $IP --------"
sshpass -p "$PASS" ssh -o "StrictHostKeyChecking=no" "$USER@$IP" "$COMMAND"
done
调用 host_list.txt 文件
# ip user passwd port
#-------------------------------------------
192.168.0.203 root XXX521 22
192.168.0.202 root XXX521 22
192.168.0.201 root XXX521 22
脚本文件放入Linux根目录执行命令
#1.此命令添加权限让脚本生效
chmod u+x ./command.sh
#2.修改 ssh_config 文件,把 StrictHostKeyChecking ask 修改成 StrictHostKeyChecking no 并取消注释
vi /etc/ssh/ssh_config
#3.记得每台检查一下是否安装sshpass 下面命令是安装
yum install sshpass
#检查命令
sshpass -V
使用方法
[root@node1 ~]# ./command.sh df -TH
-------- 192.168.0.203 --------
Filesystem Type Size Used Avail Use% Mounted on
devtmpfs devtmpfs 952M 0 952M 0% /dev
tmpfs tmpfs 964M 0 964M 0% /dev/shm
tmpfs tmpfs 964M 9.0M 955M 1% /run
tmpfs tmpfs 964M 0 964M 0% /sys/fs/cgroup
/dev/mapper/centos-root xfs 6.7G 1.6G 5.2G 24% /
/dev/sda1 xfs 1.1G 160M 905M 15% /boot
tmpfs tmpfs 193M 0 193M 0% /run/user/0
-------- 192.168.0.202 --------
Filesystem Type Size Used Avail Use% Mounted on
devtmpfs devtmpfs 952M 0 952M 0% /dev
tmpfs tmpfs 964M 0 964M 0% /dev/shm
tmpfs tmpfs 964M 9.0M 955M 1% /run
tmpfs tmpfs 964M 0 964M 0% /sys/fs/cgroup
/dev/mapper/centos-root xfs 6.7G 1.6G 5.2G 24% /
/dev/sda1 xfs 1.1G 160M 905M 15% /boot
tmpfs tmpfs 193M 0 193M 0% /run/user/0
-------- 192.168.0.201 --------
Filesystem Type Size Used Avail Use% Mounted on
devtmpfs devtmpfs 952M 0 952M 0% /dev
tmpfs tmpfs 964M 0 964M 0% /dev/shm
tmpfs tmpfs 964M 9.0M 955M 1% /run
tmpfs tmpfs 964M 0 964M 0% /sys/fs/cgroup
/dev/mapper/centos-root xfs 6.7G 1.6G 5.2G 24% /
/dev/sda1 xfs 1.1G 160M 905M 15% /boot
tmpfs tmpfs 193M 0 193M 0% /run/user/0
[root@node1 ~]#