Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am trying to create a bash script that will scp a script to a remote server, ssh (using an ssh key that is already installed) to the remote server, execute the uploaded script, and then delete the remote script when it is finished. I'm not clear how to run an ssh session inside a bash script. Here are the commands I use to do it from the command line:

scp my_script.sh user@www.remotesite.com:/usr/home/user/
ssh user@www.remotesite.com
>sh my_script.sh
>rm myscript.sh
>exit

How do I script the ssh portion of my command list? Thanks!

share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

ssh will execute commands passed as arguments on the remote machine. The following should do what you want:

ssh user@www.remotesite.com 'sh my_script.sh; rm my_script.sh'
share|improve this answer
    
I'd use && instead of ; if I wanted the script to not be deleted on failure. –  Ignacio Vazquez-Abrams Jun 17 '10 at 23:19
add comment

You could also skip the file copy and delete and do something like this.

cat my_script.sh | ssh user@host bash
share|improve this answer
add comment

You could also investigate the use of Fabric, a Python library for systems admin over SSH:

http://docs.fabfile.org/0.9.1/

It's super-simple to get started with but very powerful, especially across multiple servers.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.