Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative ways to issue multiple commands on a remote machine using SSH?

It appears that in this question, the answer was to separate statements with semicolons. However that could become cumbersome if we get into complex scripting with multiple if statements and complex quoted strings. I would think.

I imagine another alternative would be to simply issue multiple SSH commands one after the other, but again that would be cumbersome, plus I'm not set up for public/private key authentication so this would be asking for passwords a bunch of times.

What I'd ideally like is much similar to the interactive shell experience: at one point in the script you ssh into@the_remote_server and it prompts for the password, which you type in (interactively) and then from that point on until your script issues the "exit" command, all commands in the script are interpreted on the remote machine.

Of course this doesn't work:

ssh [email protected]
  cd some/dir/on/remote/machine
  tar -xzf my_tarball.tgz
  cd some/other/dir/on/remote
  cp -R some_directory somewhere_else
exit

Is there another alternative? I suppose I could take that part right out of my script and stick it into a script on the remote host. Meh. Now I'm maintaining two scripts. Plus I want a little configuration file to hold defaults and other stuff and I don't want to be maintaining that in two places either.

Is there another solution?

like image 668
Tom Auger Avatar asked Jul 14 '11 22:07

Tom Auger


People also ask

Can be used to run multiple commands one after the other?

The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command succeeds.


2 Answers

Use a heredoc.

ssh [email protected] << EOF
cd some/dir/on/remote/machine
tar -xzf my_tarball.tgz
cd some/other/dir/on/remote
cp -R some_directory somewhere_else
EOF
like image 92
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 07:09

Ignacio Vazquez-Abrams


Use heredoc syntax, like

ssh [email protected] <<EOD
 cd some/dir/on/remote/machine
 ...
EOD

or pipe, like

echo "ls -al" | ssh [email protected]
like image 26
wonk0 Avatar answered Sep 30 '22 09:09

wonk0