How to execute changes on remote server as root?

You can run local scripts remotely by executing bash on the remote system and feeding it your script

$ ssh user@host 'bash -s' <


To execute commands that require using sudo on a remote machine use ssh's -t option and pass the commands to ssh. The -t option allocates a psuedo tty and enables user interaction with the commands ran by ssh, such as entering a password for sudo

$ ssh user@host -t 'sudo foo'

To modify a file using this method sed is recommended over a redirect > because shell redirection does not allow for writing files when using sudo. Additionally, all variables in the sed command need to be escaped when they are passed to ssh.

$ ssh user@host -t 'sudo sed -i "\$a text to insert" /path/to/file'

To automate the whole thing:

SERVERS=( server1 server2 server3 )

for HOST in ${SERVERS[@]}; do 
    ssh user@${HOST} -t 'sudo sed -i "\$a text to insert" /path/to/file'

    if [[ $? -ne 0 ]]; then
        echo "ERROR: $HOST did not complete"
        echo "$HOST complete"