How to Copy Files Between Servers Using a Bash Script?
Introduction:
When managing multiple servers, it’s common to transfer files between them. Using a Bash script with scp
(secure copy), We can automate this task efficiently.
Prerequisites:
- Remote user credentials
- Install the sshpass service.
- Remote server path.
Step1 :
Bash Script to Copy a File with SSH Port and Password.
Save the script as script_file.sh
.
#!/bin/bash
# Prompt for inputs
read -p "Enter the full path of the local file to copy: " SOURCE_FILE
read -p "Enter remote SSH username: " DEST_USER
read -p "Enter remote server IP or hostname: " DEST_HOST
read -p "Enter SSH port number (e.g. 22): " SSH_PORT
read -p "Enter full remote destination path (e.g. /home/user/): " DEST_PATH
read -s -p "Enter SSH password: " SSH_PASS
echo ""
# Run SCP using sshpass with custom port
sshpass -p "$SSH_PASS" scp -P "$SSH_PORT" "$SOURCE_FILE" "$DEST_USER@$DEST_HOST:$DEST_PATH"
# Check the result
if [ $? -eq 0 ]; then
echo "✅ File copied successfully."
else
echo "❌ File copy failed!"
fi
Step 2:
Make the file executable
$chmod +x script_file.sh |
Step 3:
Run the file with the command below.
$ ./script_file.sh or $ sh script_file.sh |
Step 4:
Follow the prompts and enter the required details.
Conclusion:
This Bash script provides a quick way to transfer files between servers using scp
a custom SSH port and password authentication. While it’s convenient for controlled or temporary environments, always prioritise key-based authentication for production environments to maintain security