9

I need to write a script that will SSH into a remote host, then run certain commands on that remote host, then exit. If I just do

ssh $host

#some command

the script will SSH in, wait until I manually exit, then run the commands.

How do I run those commands on the remote host?

1
  • You can also use fabric (fabfile.org) Commented Aug 29, 2012 at 19:02

2 Answers 2

21
ssh $host 'command1; command2; command3'

or if you have just one command:

ssh $host command1

or if you have many commands (a script file):

cat file | ssh $host sh
Sign up to request clarification or add additional context in comments.

3 Comments

how would we modify the third option if there are arguments that need to be passed?
I want to run a command when ssh successfully and still keep the connection so that I can do the other task, but with this solution, the connection auto close
@TrungNguyen: you can do something like: ssh [email protected] -t 'cd /some/where; bash -l', but you can't do it directly
1

This can be used too, if you have multiple servers.

for ((i=1; i <= 10; i++))
do
echo $i
ssh host$i << EOF
cd /somedir
command1;
command2;
EOF
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.