I am trying to create a SSH Bash wrapper function that will allow me to execute commands remotely. The goal is to have a function name and parameters that are passed to the function without worry of how to escape quoting. The secondary goal (although not as important) is to capture the result of the executed command.
I have tried various methods but none of them seem to work within a function.
Here are two different methods I feel I have come the closest to the desired result with:
#!/bin/bash
s="srvr01"
ss="srvr02"
# Run commands on primary
function ssh1() {
printf -v var "%s" "$*"
ssh root@$s <<END
x() {
$*
}
x "$var"
END
}
# Run commands using secondary method
function ssh2() {
printf -v var_str "%s" "$*"
ssh -T -p 22 root@$ss $var_str
}
sshb() {
ssh1 $*
ssh2 $*
}
ssh1 echo 'net.ipv4.ip_nonlocal_bind=1' >> /etc/sysctl.conf
ssh2 echo 'net.ipv4.ip_nonlocal_bind=1' >> /etc/sysctl.conf
By passing the function to ssh and then calling it I would've expected the commands to be executed in a safely escaped manner instead of getting:
line 27: /etc/sysctl.conf: Permission denied
line 28: /etc/sysctl.conf: Permission denied
>>as a redirection operator before it even tries to determine what the arguments tossh1orssh2are; you must quote it.