bash – Connecting to a server via ssh

Question:

I want to know how I can connect to a server via SSH putting all the data ( user , host , password ) in a script .sh ,

I need this script .sh to be executed automatically by cron and to access a database on the server. I have the following code but I don't know how to get my hands on it

#!/bin/bash 
HOST="aqui_pon_la_maquina_remota" 
USER="aqui_pon_el_usuario_remoto" 
PASS="aqui_pon_el_password_remoto" 
CMD=$@ 
VAR=$(expect -c " 
spawn ssh -o StrictHostKeyChecking=no $USER@$HOST $CMD 
match_max 100000 
expect \"*?assword:*\" 
send -- \"$PASS\r\" 
send -- \"\r\" 
expect eof 
") 
echo "===============" 
echo "$VAR"

Answer:

Based on what you tell us, we are going to start by making sure that the expect command is installed, so in the console you will execute:

sudo apt-get -y install expect

Which will return something like this if you already have it installed:

Reading package list… Done
Creating dependency tree
Reading status information… Done
expect is already in its most recent version (5.45-7).
0 updated, 0 new to install, 0 to remove, and 0 not updated.

If you do not have it installed, it will simply install it, now, you are going to change your script for this:

#!/usr/bin/expect
spawn ssh user@host "ls -l ~;" # Entre comillas van tus comandos, para ejecutar varios simplemente puedes separarlos con un *punto y coma ;*
expect "password:"
send "YOUR_PASSWORD\r"
interact

Then, to execute it, we are not going to do it like with any other .sh file through an sh script.sh but we will execute it as follows:

/usr/bin/expect script.sh

And voila, the console will give you something like this (depending on the commands you send to it, obviously):

spawn ssh user@host ls -l ~;
user@host's password:
total 4
drwxr-xr-x 2 root root 4096 May 19 2016 tmp

Note: the user@host's password: prompt will still appear but you shouldn't write anything, just wait for the interact to be executed

Scroll to Top