我有一些树莓派在 ssh 服务器上创建反向 ssh 隧道。从该服务器我可以连接所有树莓派。我想创建一个 bash 脚本,该脚本将在此 ssh 服务器上运行,从所有树莓派收集一些信息并生成 html 报告。我已经有一些东西可以工作了,它只连接到一个树莓派上。我需要以某种方式循环它,以便它能够连接到所有树莓派。
必须以某种方式循环的变量是 $port,因为每个树莓派都连接到 ssh 服务器上的唯一端口,并且服务器可以从该端口连接回树莓派。
我猜它必须是这样的...对于 ports.txt 中的每个 $port 执行以下命令并将结果放入 html 表中
#!/bin/bash
cpu="$(ssh -o StrictHostKeyChecking=no $user@localhost -p $port echo $[100-$(vmstat|tail -1|awk '{print $15}')]"%")"
dsk="$(ssh -o StrictHostKeyChecking=no $user@localhost -p $port df -h /dev/mmcblk0p2 | awk 'NR>1{print $5}')"
mem="$(ssh -o StrictHostKeyChecking=no $user@localhost -p $port free | grep -e-/+ | awk '{print $3/($3+$4) * 100.0 ''}' | cut -d '.' -f1)"
tmp="$(ssh -o StrictHostKeyChecking=no $user@localhost -p $port /opt/vc/bin/vcgencmd measure_temp | sed -e 's/temp=//')"
mda="$(ssh -o StrictHostKeyChecking=no $user@localhost -p $port /bin/ls -R -l /$user/media | /usr/bin/wc -l)"
echo '<html>'
echo '<head>'
echo '<title>BeatBox Report</title>'
echo '</head>'
echo '<body>'
echo '<table border="1" align="center">'
echo '<tr>'
echo '<td></td>'
echo '<td>CPU Usage</td>'
echo '<td>Disk Usage</td>'
echo '<td>Memory Usage</td>'
echo '<td>Temperature</td>'
echo '<td>Media Count</td>'
echo '</tr>'
echo '<tr>'
echo '<td>Client001</td>'
echo "<td align="center">$cpu</td>"
echo "<td align="center">$dsk</td>"
echo "<td align="center">$mem%</td>"
echo "<td align="center">$tmp</td>"
echo "<td align="center">$mda</td>"
echo '</tr>'
echo '<tr>'
echo '<td>Client002</td>'
echo "<td align="center">$cpu</td>"
echo "<td align="center">$dsk</td>"
echo "<td align="center">$mem%</td>"
echo "<td align="center">$tmp</td>"
echo "<td align="center">$mda</td>"
echo '</tr>'
echo '<tr>'
echo '<td>Client003</td>'
echo "<td align="center">$cpu</td>"
echo "<td align="center">$dsk</td>"
echo "<td align="center">$mem%</td>"
echo "<td align="center">$tmp</td>"
echo "<td align="center">$mda</td>"
echo '</tr>'
echo '</table>'
echo '</body>'
echo '</html>'
答案1
我建议将现有代码重构为函数 ( get_stats
) 并从while
循环中调用此函数,该循环从端口文件中读取每个端口号(假设每行一个数字):
#!/bin/bash
function get_stats {
local port=$1
local cpu="..."
local dsk="..."
# ... remaining assignments ...
# Output an HTML table row for this client
echo '<tr>'
echo "<td>Client on port $port</td>"
echo "<td align='center'>$cpu</td>"
# ... echo remaining vars in similar fashion ...
echo '</tr>'
}
# Print HTML intro
echo '<html>'
# ... more html code until end of table header ...
echo '<td>Media Count</td>'
echo '</tr>'
# Print statistics for each client in turn - one table row per client
portfile='ports.txt'
while read port; do
get_stats $port
done <$portfile
# Print HTML outro
echo '</table>'
echo '</body>'
echo '</html>'