能够实现自动化运维的有很多,比如Ansible,Puppet,SaltStack,那么今天给大家分享的是我自己用Shell实现的一个可以批量远程执行的工具,写着玩的,供大家参考学习,欢迎大家多提建议。
注意:该脚本使用了expect,所以需要提前安装
[root@localhost ~]# cat remote-group-command.sh
#!/bin/bash
# 定义配置文件名称
file_name="hosts.cfg"
# 定义函数来获取指定组的配置信息
get_group_info() {
local group_name=$1
local ip
local user
local password
local port
local cmd=$2
local info=$(awk -v group="$group_name" '
$0 ~ "^\\[" group "\\]$" { test=1; next }
$0 ~ "^\\[" { test=0 }
test && /^[^[:space:]]+/{ print $1, $2, $3, $4 }
' "$file_name")
echo "$info" | while IFS= read -r line;do
# 获取相关信息
ip=$(echo "${line}" | awk '{print $1}')
user=$(echo "${line}" | awk '{print $2}' | awk -F '=' '{print $2}')
password=$(echo "${line}" | awk '{print $3}' | awk -F '=' '{print $2}')
port=$(echo "${line}" | awk '{print $4}' | awk -F '=' '{print $2}')
# 执行命令
runcmd "${ip}" "${user}" "${password}" "${port}" "${cmd}"
done
}
# 执行命令
runcmd() {
local hostip=$1
local user=$2
local password=$3
local port=$4
local cmd=$5
expect << EOF
# 开启一个进程跟踪 ssh 命令,expect 只能捕捉该进程信息
spawn ssh -p ${port} ${user}@${hostip}
expect {
"(yes/no)"
# 匹配的(yes/no)时自动输入yes,exp_continue 表示允许 expect 继续向下执行指令
{send "yes\r"; exp_continue}
"*password"
{send "${password}\r"}
}
expect "*#" {send "${cmd}\r"}
expect "*#" {send "exit\r"}
# 等待结束标记
expect eof;
EOF
}
# 判断hosts.cfg是否有指定的组
check_group() {
local group=$1
grep -w "\[${group}\]" ${file_name} > /dev/null 2>&1
if [[ "$?" -eq 0 ]]; then
return 0
else
return 1
fi
}
main() {
while getopts "h:g:c:" opt; do
case $opt in
h)
file_name=$OPTARG
;;
g)
group=$OPTARG
;;
c)
cmd=$OPTARG
if [ -z "$cmd" ]; then
echo "no command"
exit 1
fi
;;
\?)
echo "Usage: $0 -h hosts.cfg -g group -c cmd"
exit 1
esac
done
check_group $group
if [[ "$?" -eq 0 ]]; then
get_group_info $group $cmd
else
echo "group $group not exists"
exit 2
fi
}
# 检查是否传递了参数给脚本,如果没有,则显示帮助手册
if [[ $# -eq 0 ]]; then
main -?
exit 0
fi
main "$@"
[root@localhost ~]# cat hosts.cfg
[test]
192.168.207.165 username=root password=123 port=22
192.168.207.166 username=root password=123 port=22
[kgc]
192.168.207.167 username=root password=123 port=22
192.168.207.168 username=root password=123 port=22
192.168.207.169 username=root password=123 port=22
[root@localhost ~]# chmod +x remote-group-command.sh
[root@localhost ~]# ./remote-group-command.sh -g test -c "ls"
标签:脚本,Shell,group,批量,root,print,password,local,port
From: https://blog.csdn.net/qq_33906471/article/details/139468236