Connexion to a server via ssh

4

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

I need this script .sh to be executed automatically by cron and that this access a database on the server . I have the following code but I do not know how to put a hand on it

#!/bin/bash 
HOST="aqui_pon_la_maquina_remota" 
USER="aqui_pon_el_usuario_remoto" 
PASS="aqui_pon_el_password_remoto" 
[email protected] 
VAR=$(expect -c " 
spawn ssh -o StrictHostKeyChecking=no [email protected]$HOST $CMD 
match_max 100000 
expect \"*?assword:*\" 
send -- \"$PASS\r\" 
send -- \"\r\" 
expect eof 
") 
echo "===============" 
echo "$VAR"
    
asked by Maro 24.11.2016 в 17:30
source

2 answers

1

Starting from what you tell us, let's start by making sure that the command expect is installed, so in the console you will execute a:

sudo apt-get -y install expect

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

  

Reading list of packages ... Done
  Creating dependency tree
  Reading the status information ... Done
  expect is already in its most recent version (5.45-7).
  0 updated, 0 new will be installed, 0 to delete and 0 not updated.

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

#!/usr/bin/expect
spawn ssh [email protected] "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 will not do it as with any other .sh file using a sh script.sh if not that we will execute it in the following way:

/usr/bin/expect script.sh

And voila, the console will give you something like this (depending on the commands you send, 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% equal% prompt will appear but you will not have to write anything, just wait for [email protected]'s password: to run

    
answered by 24.11.2016 в 18:30
1

If at any time that password changes, the script stops making sense.

I think in this case and given that it's a cron the best thing you can do is copy the key ssh and then set your ssh to connect automatically.

Copy ssh: ssh-copy-id [email protected]

And then in ~/.ssh/config :

Host nombreServidor
Hostname host
User root
Port 22

I'll give you an example, if I wanted to connect to a computer on my local network called serverPruebas with IP 192.168.1.2

Host servidorPruebas
Hostname 192.168.1.2
User root
Port 22

This way only with writing ssh servidorPruebas the system connects without password.

And if I ever change the password, I do not have to worry, because I connect using ssh key .

    
answered by 25.11.2016 в 11:08