How to ssh from within a bash script?

BashSsh

Bash Problem Overview


I am trying to create an ssh connection and do some things on the remote server from within the script.

However the terminal prompts me for a password, then opens the connection in the terminal window instead of the script. The commands don't get executed until I exit the connection.

How can I ssh from within a bash script?

Bash Solutions


Solution 1 - Bash

  1. If you want the password prompt to go away then use key based authentication (described here).

  2. To run commands remotely over ssh you have to give them as an argument to ssh, like the following:

> root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'

Solution 2 - Bash

If you want to continue to use passwords and not use key exchange then you can accomplish this with 'expect' like so:

#!/usr/bin/expect -f
spawn ssh user@hostname
expect "password:"
sleep 1
send "<your password>\r"
command1
command2
commandN

Solution 3 - Bash

There's yet another way to do it using Shared Connections, ie: somebody initiates the connection, using a password, and every subsequent connection will multiplex over the same channel, negating the need for re-authentication. ( And its faster too )

# ~/.ssh/config 
ControlMaster auto
ControlPath ~/.ssh/pool/%r@%h

then you just have to log in, and as long as you are logged in, the bash script will be able to open ssh connections.

You can then stop your script from working when somebody has not already opened the channel by:

ssh ... -o KbdInteractiveAuthentication=no ....

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewView Question on Stackoverflow
Solution 1 - BashhalfdanView Answer on Stackoverflow
Solution 2 - BashSiegeXView Answer on Stackoverflow
Solution 3 - BashKent FredricView Answer on Stackoverflow