0

I try to migrate shell code to Python fabric code. The issue I meets is that Python can not execute command with root in a remote Linux host. Could anyone meet this issue and figure it out? I am very appreciate for your help. Thanks in advance.

TestHost1="host01 host02 host03"
for host in $TestHost1
do sshpass -p password ssh -T -q -o UserKnownHostsFile=/dev/null \
                           -o StrictHostKeyChecking=no username@$host << EOL;
sudo su -
sed -i 's/10./172./g'/etc/hosts
EOL
done

2 Answers 2

1

Try to execute it on this way:

TestHost1="host01 host02 host03"
for host in $TestHost1
do sshpass -p password ssh -T -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username@$host "sudo sed -i 's/10./172./g'/etc/hosts"

done
1
  • Thanks Romeo. For security policy in my company hosts, admin user can't directly run sudo command except "sudo su - root" . In that way, I have to su to root before I run any command which needs root permission.
    – Sam
    Commented May 17, 2015 at 3:22
1

In order for sudo to be able to prompt for a password you need to give it a tty device (a pseudo-tty). ssh will usually create the pseudo-tty device on the remote end if its input is also from a terminal. However, in this case it isn't - you're using a heredoc (the << bit).

To copy your style, you need to add the RequestTTY option to ssh, also available implemented as -t. Confusingly you have explicitly disabled pseudo-tty allocation with your -T flag, so you need to replace that:

TestHost1="host01 host02 host03"
for host in $TestHost1
do sshpass -p password ssh -t -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username@$host << EOL;
sudo su -
sed -i 's/10./172./g' /etc/hosts
EOL
done

However, you might want to review your replacement match 10.; as it stands that matches the two characters 10 plus any one character (the . is a wildcard), multiple times per line. Perhaps it should be 10\. (match three literal characters) or even ^10\. (match three literal characters at the start of the line). Here I've assumed you meant three literal characters 10. at the start of the line:

TestHost1="host01 host02 host03"
for host in $TestHost1
do sshpass -p password ssh -t -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username@$host sudo sed -i.bak 's/^10\./172./' /etc/hosts
done
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .