0

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?

ayushgp
  • 4,891
  • 8
  • 40
  • 75

2 Answers2

2

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 which also discusses how to provide passwords. One of these ought to help you out. :)

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36
1

If you can install a python package on your machine, then Fabric 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, but it is not as smooth as Fabric, so I would not recommend it.

Samarth
  • 627
  • 6
  • 13