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 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.
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.
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.
If you want the password prompt to go away then use key based authentication (described here).
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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With