`ssh` treat remote command as hostname

Viewed 29

I am writing a bash script to read from MPI style hostfile and execute remote command with ssh.

while read p; do
    arrP=($p)
    ssh_target=${arrP[0]}
    echo ${ssh_target}
    ssh ${ssh_target} "pkill python" < /dev/null

done <hostfile

The content of hostfile is

ec2-34-214-59-113.us-west-2.compute.amazonaws.com slots=1
ec2-34-220-248-224.us-west-2.compute.amazonaws.com slots=1

I got the following error:

Pseudo-terminal will not be allocated because stdin is not a terminal.
ssh: Could not resolve hostname pkill python: Name or service not known

I try to manually run the commandline from shell:

ssh ec2-34-214-59-113.us-west-2.compute.amazonaws.com "pkill python"

and it runs successfully. Thus I assume there may be something wrong in the way I construct the command but I couldn't find it. If I remove the < /dev/null from ssh command, it will run successfully but it will also break the while loop. I tried to use -n and -t but I got the same error. Any comments and suggestions are welcome. Thanks!

1 Answers

@user1934428 's comment of ssh_target being empty and using set -x is right to the target. From the following output it can be seen that the empty line in hostfile is the root cause.

$ ./kill_python_dist.sh
++ read p
++ arrP=($p)
++ ssh_target=ec2-34-214-59-113.us-west-2.compute.amazonaws.com
++ echo ec2-34-214-59-113.us-west-2.compute.amazonaws.com
ec2-34-214-59-113.us-west-2.compute.amazonaws.com
++ echo ec2-34-214-59-113.us-west-2.compute.amazonaws.com
ec2-34-214-59-113.us-west-2.compute.amazonaws.com
++ ssh ec2-34-214-59-113.us-west-2.compute.amazonaws.com 'pkill python'
++ read p
++ arrP=($p)
++ ssh_target=ec2-34-220-248-224.us-west-2.compute.amazonaws.com
++ echo ec2-34-220-248-224.us-west-2.compute.amazonaws.com
ec2-34-220-248-224.us-west-2.compute.amazonaws.com
++ echo ec2-34-220-248-224.us-west-2.compute.amazonaws.com
ec2-34-220-248-224.us-west-2.compute.amazonaws.com
++ ssh ec2-34-220-248-224.us-west-2.compute.amazonaws.com 'pkill python'
++ read p
++ arrP=($p)
++ ssh_target=
++ echo

++ echo

++ ssh 'pkill python'
Pseudo-terminal will not be allocated because stdin is not a terminal.
ssh: Could not resolve hostname pkill python: Name or service not known

I updated the bash script to check for the empty line and the error is gone

while read p; do
    arrP=($p)
    ssh_target=${arrP[0]}
    if [ -z "${ssh_target}" ]; then
        continue
    fi
    echo ${ssh_target}
    ssh ${ssh_target} "pkill python" < /dev/null

done <hostfile
Related