我目前正在编写以下脚本登录到远程服务器并运行几个命令来验证服务器的性能并根据这些命令的输出打印一条消息。但是 ssh 不起作用并返回托管脚本的服务器的统计信息。
脚本
#!/bin/bash
#######################
#Function to add hosts to the array
#the following function takes the ip addresses provided while the script is run and stores them in an array
#######################
Host_storing_func () {
HOST_array=()
for i in $@ ;do
HOST_array+=(${i});
done
#echo ${HOST_array[*]}
}
#######################
#Calling above function
#######################
Host_storing_func "$@"
############################################################
#Collect Stats of Ping,memory,iowait time test function
############################################################
b=`expr ${#HOST_array[*]} - 1 `
for i in `seq 0 $b` ;do
sshpass -f /root/scripts/passwordFile.txt /usr/bin/ssh student35@${HOST_array[${i}]} << HERE
echo `hostname`
iowaittm=`sar 2 2|awk '/^Average/{print $5};'`
if [ $iowaittm > 10 ];then
echo "IO ==> BAD"
else
echo "IO ==> GOOD"
fi
memoryy=`free -m |grep Swap|awk '{if($2 == 0) print 0;else print (($4 / $2 ) * 100)}'`
if [ ${memoryy} < '10' ] ;then
echo "memory ==> good"
elif [[ "${memory}" -ge 0 ]] && [[ "${memory}" -le 10 ]];then
echo "No Swap"
else
echo "memory ==> bad"`enter code here`
fi
ping -w2 -c2 `hostname` | grep "packet loss"|awk -F, '{print $3}'|awk -F% '{print $1}'|sed 's/^ *//'|awk '{if ($1 == 0) print "Yes" ;else print "No"}'
HERE
done
输出:oc5610517603.XXX.com是源服务器的名字
[root@oc5610517603 scripts]# ./big_exercise.sh 9.XXX.XXX.XXX 9.XXX.XXX.XXX
Pseudo-terminal will not be allocated because stdin is not a terminal.
oc5610517603.XXX.com
IO ==> GOOD
No Swap
ping: oc5610517603.ibm.com: Name or service not known
Pseudo-terminal will not be allocated because stdin is not a terminal.
oc5610517603.XXX.com
IO ==> GOOD
No Swap
ping: oc5610517603.XXX.com: Name or service not known
最佳答案
感谢您检查脚本,我找到了解决问题的方法
导致问题的是 sshpass 命令,如果你想在 HEREdoc 中使用变量,你只需将开头的 HERE 放在单引号中,但如果变量是在 ssh 之前计算的,那么你不必把以单引号打开 HERE
sshpass -f/root/scripts/passwordFile.txt/usr/bin/ssh -T student35@${i} << '这里'
在我如上所述更改 sshpass 命令后,我的脚本运行了
关于bash - 如何使用 bash 脚本在远程 Linux 服务器上运行多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49615633/