Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ssh from within a bash script?

Tags:

bash

ssh

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?

like image 745
Andrew Avatar asked Dec 13 '09 00:12

Andrew


People also ask

Can I SSH in a bash script?

Bash script SSH is a common tool for Linux users. It is needed when you want to run a command from a local server or a Linux workstation. SSH is also used to access local Bash scripts from a local or remote server.

What is the SSH command in bash?

The ssh command provides a secure encrypted connection between two hosts over an insecure network. This connection can also be used for terminal access, file transfers, and for tunneling other applications. Graphical X11 applications can also be run securely over SSH from a remote location.

What is SSH in shell script?

ssh stands for “Secure Shell”. It is a protocol used to securely connect to a remote server/system. ssh is secure in the sense that it transfers the data in encrypted form between the host and the client. It transfers inputs from the client to the host and relays back the output. ssh runs at TCP/IP port 22.


2 Answers

  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'

like image 103
halfdan Avatar answered Sep 21 '22 23:09

halfdan


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 
like image 20
SiegeX Avatar answered Sep 23 '22 23:09

SiegeX