Try this:
#!/bin/bash
while read f; do
sshpass -p "mypassword" ssh-copy-id myusername@"$f"
ssh -ntt myusername@"$f" '
echo mypassword | sudo -S touch /etc/sudoers.d/10_icinga_check_postfix_queue || true
echo mypassword | sudo -S bash -c "echo \"icinga ALL=(ALL) NOPASSWD: /usr/lib64/nagios/plugins/check_postfix_queue, /usr/lib64/nagios/plugins/contrib/restart_service.sh\" > /etc/sudoers.d/10_icinga_check_postfix_queue" || true' </dev/null
done < linux-list.txt
This will run the entire echo ... >file
command in a sudo shell (rather than just running echo
with sudo, and the >file
part unprivileged). The tricky thing here is the quoting: there's a single-quoted string that's being passed to ssh
as an argument (the commands to run on the remote computer); inside that, there's a double-quoted string being passed to bash -c
as the command run (as root), and inside that, there's another quoted string. Since quotes don't nest, the innermost quoted string uses escaped double-quotes (\"
), which get passed unchanged when the single-quoted string is parsed on the local computer, then when the outer double-quoted string gets parsed by the remote shell the escapes get removed, so by the time the remote root shell sees it, it's a normal double-quoted string. Yes, this is a mess, but it should work (though I haven't tested it).