theillien
theillien

Reputation: 1380

Scripting sudo via SSH behaves strangely when reading from file

I've discovered that I can run a single sudo command on a remote system from within a bash script. For example:

#!/bin/bash

ssh -t <REMOTE_IP> 'sudo ls /root'

However, if I try to run the same command via a loop over a file containing the IPs of the remote systems it starts to get weird. It fails to allocate a TTY with the -t option so I use two (-t -t). Doing this gets it to the password prompt. It then tells me my password was incorrect when I didn't even enter one, displays a second prompt which echos my password back and then hangs after I hit enter.

An example of such a script:

#!/bin/bash

while read i
do
    ssh -t -t $i "sudo ls /root"
done < ip.list

Example of the results I'm seeing:

user@opensuse:~/bin> ./test.sh 
10.153.171.131

[sudo] password for user: 
Sorry, try again.
[sudo] password for user: Pa55w0rd
^CKilled by signal 2. *This is where it hangs and I have to kill it.*

I haven't found much in the way of an explanation so if anyone can shed some light on this I'd be most grateful.

Thanks.

Upvotes: 2

Views: 2142

Answers (1)

Bob the Angry Coder
Bob the Angry Coder

Reputation: 1344

You are redirecting stdin inside your loop:

while read i
do
    ssh -t -t $i "sudo ls /root"
done < ip.list

This means that (a) ssh is no longer connected to your TTY, and (b) it's probably going to eat your input. Ideally, you would redirect input to ssh from /dev/null and configure sudo to not require a TTY. However, you can try:

ssh -t $i "sudo ls /root" < /dev/tty

Upvotes: 3

Related Questions