bash - 如何使用 bash 脚本在远程 Linux 服务器上运行多个命令

标签 bash

我目前正在编写以下脚本登录到远程服务器并运行几个命令来验证服务器的性能并根据这些命令的输出打印一条消息。但是 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/

相关文章:

bash - 如何从 C 执行 bash 命令?

linux - 如何在 Linux 中仅使用 fs 和 bash 从 IPv4 ip 地址获取接口(interface)名称?

linux - 检查脚本是否正在运行并启动它的脚本,如果它已停止

html - MYSQL 输出到现有的 HTML 模板

r - 从 Bash 访问 R 的环境变量

python - 从 Python 或 R 中的文件名列表中提取子字符串

bash - 在 xterm 中,我可以在不重置当前颜色的情况下关闭粗体或下划线吗?

正则表达式移动和更改文件名

linux - 将多个文本 block 提取到一个新文件中

linux - 为什么管道上的这个 strace 没有完成