2

I'm looking to list all files in a folder:

ABC123.cfg
XYZ456.cfg
EFG999.cfg

The file names, without the .cfg relate to a remote server name, ABC123 etc.

I want to copy a couple of files to each of the remote servers.

So, look up the filenames, but take the name without the .cfg. Then

scp filename.txt username@ABC123:/home/username/

For each remote server, overwriting the destination file if exists.

Each remote server uses the same username and password. Can I use a password in the scp command?

dessert
  • 39,982

1 Answers1

4

This should do the job:

#!/bin/bash
for i in *.cfg; do
  sshpass -f /path/to/passwordfile scp ${i%.cfg}.txt username@${i%.cfg}:
done

or rather

for i in *.cfg;do sshpass -f /path/to/passwordfile scp ${i%.cfg}.txt username@${i%.cfg}:;done

The password is passed to scp using sshpass (following How to pass password to scp?) which reads it from passwordfile – remember to secure this file against unauthorized read access with chmod 400!

I got a little bit confused what file you want to send here, I understood there's e.g. a file ABC123.txt that has to be sent to host ABC123, so I just stripped .cfg using Bash Parameter Expansion and added .txt.

As user@host: defaults to user's home directory I removed the path.

dessert
  • 39,982
  • AWESOME, thanks. I was closer than I thought, but couldn't get it 100%. – Preston Cole Dec 02 '17 at 14:42
  • Please, don't use sshpass -p. Even its manual notes that it's not very safe on most systems. Just use SSHPASS=$password sshpass -e ... instead. – ilkkachu Dec 02 '17 at 18:54
  • @ilkkachu You're totally right, I changed the whole answer to suggest a much safer approach. Thank you! – dessert Dec 02 '17 at 19:20
  • Though you could spare the user the trouble of making a file, and ask them for the password from the script and put in the envvar, something like read -rs pass; SSHPASS=$pass sshpass -e ... But then we're probably getting to the point where using ssh keys and ssh-agent would be smartest – ilkkachu Dec 02 '17 at 19:58