How ssh from bash script?

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

However, the terminal asks me for the password, and then opens a connection in the terminal window instead of the script. Commands are not executed until I exit the connection.

How can I get ssh from a bash script?

+41
bash ssh
Dec 13 '09 at 0:33
source share
4 answers
  • If you want the password prompt to disappear, use key-based authentication ( described here ).

  • To run commands remotely via ssh, you must specify them as an ssh argument, for example:

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

+52
Dec 13 '09 at 0:38
source share

If you want to continue to use passwords and not use key exchange, you can accomplish this with "expect" as follows:

#!/usr/bin/expect -f spawn ssh user@hostname expect "password:" sleep 1 send "<your password>\r" command1 command2 commandN 
+14
Dec 13 '09 at 0:54
source share

There is another way to do this using shared connections, that is: someone initiates a connection using a password, and each subsequent connection will be multiplexed on the same channel, which negates the need for re-authentication. (And even faster)

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

you just need to log in, and while you log in, the bash script will be able to open ssh connections.

Then you can stop the script from working if someone else has not opened the channel by clicking

 ssh ... -o KbdInteractiveAuthentication=no .... 
+3
Dec 13 '09 at 10:25
source share

What you need to do is SSH key exchange for the user the script is working with. Check out this tutorial

After that, your scripts will work without having to enter a password. But, for security's sake, you do not want to do this for root users!

+2
Dec 13 '09 at 0:36
source share



All Articles