Reputation: 495
I'm getting incredibly frustrated here. I simply want to run a sudo command on a remote SSH connection and perform operations on the results I get locally in my script. I've looked around for close to an hour now and not seen anything related to that issue.
When I do:
#!/usr/bin/env bash
OUT=$(ssh username@host "command" 2>&1 )
echo $OUT
Then, I get the expected output in OUT.
Now, when I try to do a sudo command:
#!/usr/bin/env bash
OUT=$(ssh username@host "sudo command" 2>&1 )
echo $OUT
I get "sudo: no tty present and no askpass program specified". Fair enough, I'll use ssh -t.
#!/usr/bin/env bash
OUT=$(ssh -t username@host "sudo command" 2>&1 )
echo $OUT
Then, nothing happens. It hangs, never asking for the sudo password in my terminal. Note that this happens whether I send a sudo command or not, the ssh -t hangs, period.
Alright, let's forget the variable for now and just issue the ssh -t command.
#!/usr/bin/env bash
ssh -t username@host "sudo command" 2>&1
Then, well, it works no problem.
So the issue is that ssh -t inside a variable just doesn't do anything, but I can't figure out why or how to make it work for the life of me. Anyone with a suggestion?
Upvotes: 3
Views: 1258
Reputation: 4525
In this situation, you can use tee
to reveal the sudo
prompt while also capturing the output of the ssh
command in a temp file.
tempfile=$(mktemp)
ssh -t username@host "sudo command" | tee $tempfile
Keep in mind that this will also capture the sudo
prompt and all stderr
output from the remote shell in the output file, because stdout
& stderr
are both connected to the client shell's stdout
when using ssh -t
.
Upvotes: 0
Reputation: 3150
If your script is rather concise, you could consider this:
#!/usr/bin/env bash
ssh -t username@host "sudo command" 2>&1 \
| ( \
read output
# do something with $output, e.g.
echo "$output"
)
For more information, consider this: https://stackoverflow.com/a/15170225/10470287
Upvotes: 3