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?

| improve this question | | | | |
  • 1
    Why not set up passwordless access using ssh keys? It's simpler and more secure than password authentication anyway. – terdon Jul 4 '17 at 16:59

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.

| improve this answer | | | | |

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";

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
| improve this answer | | | | |
  • 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 4 '17 at 18:17
  • @Jakuje, good point. Then this two scripts should be converted/merged in one. – MetNP Jul 4 '17 at 22:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.