Copy files to another host
I have a need to copy certificate files from one host to another. The certificate is only acquired from this host.
The location of the certificates is only accessible to the root user.
What I came up with is something like this:
#!/bin/bash
# setup variables
cert_dir="/etc/letsencrypt/live/mysite"
cert_file="cert.pem"
key_file="privkey.pem"
local_temp="/tmp"
target_cert_file="mydomain.pem"
target_key_file="mydomain.key"
remote_host="host2"
remote_user="user1"
remote_dir="/home/user1"
cert_target_dir="/etc/ssl/certs"
key_target_dir="/etc/ssl/private"
# Copy files to temp folder under new names
# Change file permissions to enable us to send them to the remote host without needing sudo
sudo cp $cert_dir/$cert_file $local_temp/$target_cert_file
sudo cp $cert_dir/$key_file $local_temp/$target_key_file
sudo chown myuser: $local_temp/{$target_cert_file,$target_key_file}
# copy files to remote host
scp "$local_temp/$target_cert_file" "$remote_user@$remote_host:$remote_dir/"
scp "$local_temp/$target_key_file" "$remote_user@$remote_host:$remote_dir/"
# move the files to the target destinations
ssh "$remote_user@$remote_host" "sudo mv -f $remote_dir/$target_cert_file $cert_target_dir; sudo mv -f $remote_dir/$target_key_file $key_target_dir"
# delete the temp files
rm $local_temp/{$target_cert_file;$target_key_file}
Explanations:
Copying the original files to a local temp file was the only way I could copy them without getting asked for a password, even though my user has the NOPASSWD setting in sudo.
The rest are pretty standard.