Question: Say I have a bunch of commands that I'd like to execute on my local machine and bunch of others on the remote host. For example:

```
execute_locally_then_remotely() {
    # Things I want to execute locally
    foo --bar
    foo --baz
    scp filename.gz $1:/tmp

    ssh $1
    # Execute these commands on remote host
    gunzip -xvf /tmp/filename.gz
    rm -f /tmp/filename.gz

    sudo -su otheruser
    # Bunch of other commands I'd like to execute as a different user on remote host
    foobar filename

    # Exit back to local shell and execute following commands here:
    ls
}

```

Any ideas on how to achieve all this using a shell script?

Answer: 
*If you have passwordless access* it's easy.

```
ssh user@hostname " : remote script; echo hi; date; : etc; "

```

With passwordless `sudo` on the remote, that's easy too, and pretty transparent. 

For more detailed treatment, c.f. [this post](https://stackoverflow.com/questions/10310299/proper-way-to-sudo-over-ssh) which also discusses how to provide passwords. One of these ought to help you out. :)
If you can install a python package on your machine, then [Fabric](http://docs.fabfile.org/en/2.4/cli.html) would do the trick for you. 
A sample remote command would look something like this:

```
fab -H <host1> -u <username> -p <password> -- gunzip -xvf /tmp/filename.gz

```

Another option is to use [expect](https://linux.die.net/man/1/expect), but it is not as smooth as Fabric, so I would not recommend it.