I am translating a bash program to Python and have got everything up to the last bit working. Here is the bash code, which simply SSHs into a server, executes a PostgreSQL database dump, and if there was no error, saves it to a file.
output="$(ssh "$SSH_LOCATION" bash <<< "$(printf 'PGPASSWORD=%q pg_dump -U %q %q' "$pg_pass" "$pg_user" "$database")")"
if [[ $? -ne 0 ]]
then
echo "$output"
echo "An error occurred while dumping the database"
exit $?
else
echo "$output" > ~/"$LOCAL_DIR"/"$database"
fi
The variables SSH_LOCATION, LOCAL_DIR, pg_pass, pg_user and database are all defined within the Python program.
Escaping of the variables for the remote shell, especially pg_pass, is very important. This was handled in the bash code by printf '%q'.
What is the best way to translate the above bash code to Python?
Edit: and another caveat, the authentication is handled by public key, not password. Of course, the ssh shell command handles this automatically.
subproccess.Popen(['bash', '-c', """BASH CODE"""]), and feed all the variables from python. That feels a little too hacky though.