通过 ssh 执行远程 bash 脚本导致本地脚本停止

通过 ssh 执行远程 bash 脚本导致本地脚本停止

我有一个设置,其行为方式让我无法理解。所以我有一个本地 bash 脚本generateTrafficOnHosts.sh,它从文件中读取 IP 地址。然后它getTraffic.sh在每个远程主机(即它调用的每个 IP 地址)上调用一个 bash 脚本。但是,在通过 ssh 进行第一次远程执行后,它就完成了。这是我的本地generateTrafficOnHosts.sh脚本:

#!/bin/bash
# Connects to a series of hosts and runs the get-traffic.sh script on     them. 
# The hosts are taken from a file with a list of randomly generated IDs,
# while their IDs are taken from a connectfile.

# ...
# some convenience functions here
# ...

#######################################
# runs the traffic generation script on
# a host.
# Globals:
#   
# Arguments:
#   <IP of the remote host>
# Returns:
#   None
#######################################
function run_on_host() {
    local RESULTS
    RESULTS=$(ssh -i key.pem user@"$1" '/home/user/get-traffic.sh 2>&1 >/dev/null')
}

#######################################
# Runs the load on the hosts
# Globals:
#   HOSTSFILE
# Arguments:
#   None
# Returns:
#   None
#######################################
function run_load_on_hosts() {
    while read line
    do
        local ip=$(get_ip_for_key ${line})
        echo "getting IP for key in line ${line}"
        if [[ $ip != "" ]]; then
            echo "running on host $line($ip)"
            run_on_host "${ip}"
        else
            echo "error: LINE'$line', IP'$ip'"
        fi
    done < "$HOSTSFILE"
}

function main() {
    check "$@"
    run_load_on_hosts
}

main "$@"

远程脚本get-traffic.sh如下所示:

#!/bin/bash
PORT=47111

# Time limit in seconds
TIME_LIMIT=10
# Blocksize of the dd command: how much data shall be downloaded per chunk? 
BS=1M

while [[ "$SECONDS" -le "$TIME_LIMIT" ]]; do
    # $SECONDS is a shell variable
    nc "${HOST}" "${PORT}" | dd count=1 bs="${BS}" iflag=fullblock > /dev/null
done

现在来看看奇怪的行为:脚本只针对 hosts 文件中的第一个主机运行。如果我用 替换该行ssh -i ...sleep 1; echo "running..."一切都会顺利运行。如果我用 替换远程命令/home/user/get-traffic.sh,情况也是如此ls /home/user- 一切都很好。但是,如果我用 替换远程命令,脚本也会在第一次迭代后返回ls

我已经跟踪这个错误好几个小时了,几个小时前我已经没有主意了。有人可以帮我吗?!?:|

答案1

查看ssh手册,更具体地了解-t选项。

如果这不起作用,请尝试该-tt选项。另外,我认为您的get-traffic.sh脚本应该exit 0放在最后。

相关内容