Skip to content

Instantly share code, notes, and snippets.

@ob1-sc
Created September 4, 2018 10:53
Show Gist options
  • Save ob1-sc/7f6a32b0fbe9b51ba9888bf7598da434 to your computer and use it in GitHub Desktop.
Save ob1-sc/7f6a32b0fbe9b51ba9888bf7598da434 to your computer and use it in GitHub Desktop.
Run script on remote server as sudo
#!/bin/bash
SUDO_PWD=superSecurePassword
ROOT_USER=root
SERVER=10.0.0.097879879
SCRIPT_TO_RUN=script_to_run.sh
SUDO_ECHO_SCRIPT=sudo_echo.sh
# generate script to run on remote server
cat > /tmp/${SCRIPT_TO_RUN} <<EO_SH
#!/bin/bash
# DO STUFF
echo "Hello World!"
EO_SH
# generate script that will echo sudo password to sudo
echo "echo ${SUDO_PWD} | sudo -S /tmp/${SCRIPT_TO_RUN}" > /tmp/${SUDO_ECHO_SCRIPT}
# copy scripts to server
sshpass -p ${SUDO_PWD} scp -o 'StrictHostKeyChecking=no' /tmp/${SUDO_ECHO_SCRIPT} ${ROOT_USER}@${SERVER}:tmp
sshpass -p ${SUDO_PWD} scp -o 'StrictHostKeyChecking=no' /tmp/${SCRIPT_TO_RUN} ${ROOT_USER}@${SERVER}:tmp
# run the script (as sudo)
sshpass -p ${SUDO_PWD} ssh ${ROOT_USER}@${SERVER} "chmod +x /tmp/${SUDO_ECHO_SCRIPT}; chmod +x /tmp/${SCRIPT_TO_RUN}; /tmp/${SUDO_ECHO_SCRIPT}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment