83

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?

Ben
  • 54,723
  • 49
  • 178
  • 224
Andrew
  • 227,796
  • 193
  • 515
  • 708
  • What you need to do is to exchange the SSH keys for the user the script runs as. Have a look at [this tutorial](http://oreilly.com/pub/h/66) After doing so, your scripts will run without the need for entering a password. But, for security's sake, you don't want to do this for root users! – Dan Soap Dec 13 '09 at 00:36

4 Answers4

86
  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'

halfdan
  • 33,545
  • 8
  • 78
  • 87
24

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
SiegeX
  • 135,741
  • 24
  • 144
  • 154
  • -bash: ./test.sh: /usr/bin/expect: bad interpreter: No such file or directory – Hamza Saeed Aug 06 '20 at 08:05
  • 2
    @HamzaSaeed - You need to install the expect interpreter first, try running "sudo apt-get install expect" then retry. Also I had an issue in windows when copying and pasting the interpreter line from above, try manually typing it instead in your script. –  Mar 10 '22 at 15:15
6

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 ....
Kent Fredric
  • 56,416
  • 14
  • 107
  • 150
-2

You may use the below bash script for the execution.

Please make sure to replace the "$remote_command" with your specified command which you want to execute.

ssh -p "$remote_port" "$remote_user@$remote_host" "$remote_command"
cigien
  • 57,834
  • 11
  • 73
  • 112
  • 3
    For more reference on self-promotion, please read [the relevant article in the help centre](/help/promotion). Attribution is great, actively searching for a question which has been posted in 2009 and hasn't been active since 2013 just to post a link to your log isn't. – Adriaan Aug 15 '23 at 14:45