1

I would like to compare multiple local files with their counterpart on a remote host, so I'd like to create a script like:

ssh user@remote_host "cat remote_file1.txt" | diff - local_file1.txt
ssh user@remote_host "cat remote_file2.txt" | diff - local_file2.txt
...
ssh user@remote_host "cat remote_fileN.txt" | diff - local_fileN.txt

The problem with such script is that it asks the password for each file. How to make it ask the password just once?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
kuma
  • 275
  • 1
  • 2
  • 5

2 Answers2

2

One way is to set up passwordless access (public key authentication), the other is to multiplex the connections. Create a configuration file in ~/.ssh/config with the following:

Host remote_host
  User user
  ControlPath ~/.ssh/controlmasters/%r@%h:%p
  ControlMaster auto
  ControlPersist 5m

Create a directory ~/.ssh/controlmasters/:

mkdir -m 700 ~/.ssh/controlmasters/

And then when you run the script, it should ask only once for the password and all the other commands will be ran through the same, already authenticated, connection.

Jakuje
  • 21,357
0

If you are not allowed to create passwordless access with: ssh-keygen user@remotehost, you can install common expect tool, and create script called passexpect:

#!/usr/bin/expect -f

set timeout 20
set cmd [lrange $argv 1 end]
set password [lindex $argv 0]

log_user 0
eval spawn $cmd
expect "assword:"
send "$password\r";
interact

then in main shell script, you can read password once:

printf "ssh password:" >&2; read -s pass; printf "\n">&2

and use it in any ssh command:

passexpect $pass ssh user@remotehost command_for_remote_host

or for your purpose, full script would be:

#/usr/bin/env bash
printf "ssh password:" >&2; read -s pass; printf "\n">&2
./passexpect $pass ssh user@remotehost cat remoteF1.txt | diff - localF1.txt
./passexpect $pass ssh user@remotehost cat remoteF2.txt | diff - localF2.txt
MetNP
  • 510
  • 1
    That is not a good idea to expose your password to all the other users of the system. As you run it now, the password will be visible in the ps for every user on the system. – Jakuje Jul 04 '17 at 18:17
  • @Jakuje, good point. Then this two scripts should be converted/merged in one. – MetNP Jul 04 '17 at 22:50