When I try to use an ssh command in a shell script, the command just sits there. Do you have an example of how to use ssh in a shell script?
5 Answers
Depends on what you want to do, and how you use it. If you just want to execute a command remotely and safely on another machine, just use
ssh user@host command
for example
ssh user@host ls
In order to do this safely you need to either ask the user for the password during runtime, or set up keys on the remote host.

- 19,783
- 6
- 37
- 57
-
3+1 for completeness, simplicity, and conciseness ... with an example to boot! – Adam Liss Nov 03 '08 at 12:21
First, you need to make sure you've set up password-less (public key login). There are at least two flavors of ssh with slightly different configuration file formats. Check the ssh manpage on your system, consult you local sysadmin or head over to How do I setup Public-Key Authentication?.
To run ssh in batch mode (such as within a shell script), you need to pass a command you want to be run. The syntax is:
ssh host command
If you want to run more than one command at the same time, use quotes and semicolons:
ssh host "command1; command2"
The quotes are needed to protect the semicolons from the shell interpreter. If you left them out, only the first command would be run remotely and all the rest would be run on the local machine.

- 1
- 1

- 20,880
- 12
- 98
- 148
-
2Does this exist on Mac OS or is this just a Linux thing? And yes, I did just read [how to get this hat](http://meta.stackexchange.com/a/270851/256945). Wanted to post a meaningful comment though. – Arc676 Dec 22 '15 at 06:35
You can use expect
command to populate the username/password info.

- 8,143
- 4
- 39
- 48

- 7,105
- 9
- 49
- 46
-
Do you mean the `export` command? it can be used to set the username (`LOGNAME` or `USER`) but imo not the password. – Brutus Oct 12 '11 at 19:21
The easiest way is using a certificate for the user that runs the script.
A more complex one implies adding to stdin the password when the shell command asks for it. Expect, perl libraries, show to the user the prompt asking the password (if is interactive, at least), there are a lot of choices.

- 415
- 2
- 2
-
I dont get it, sorry. I do not wonder you have been down-voted. IMHO you should try to be more specific, as it seems that you are guessing around. That surely helps no-one, to be honest. – Pille May 22 '17 at 17:33