Skip to content

Instantly share code, notes, and snippets.

@rwunsch
Last active January 22, 2025 12:22
Show Gist options
  • Select an option

  • Save rwunsch/5578753fc90798ccc56648a200528ee7 to your computer and use it in GitHub Desktop.

Select an option

Save rwunsch/5578753fc90798ccc56648a200528ee7 to your computer and use it in GitHub Desktop.
reverse-scp.sh - This script lists remote files, lets the user select them, and downloads them via SCP.
#!/bin/bash
# Function to display help message
show_help() {
echo "Usage: $0 [REMOTE_USER REMOTE_HOST REMOTE_DIR]"
echo
echo "Arguments:"
echo " REMOTE_USER SSH username for the remote connection"
echo " REMOTE_HOST Remote host (IP or domain)"
echo " REMOTE_DIR Directory on the remote server"
echo
echo "If no arguments are provided, the script will prompt for input."
exit 0
}
# Check if help flag is passed
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
show_help
fi
# Assign command-line arguments or prompt for missing parameters
if [[ -n "$1" ]]; then
REMOTE_USER="$1"
else
read -rp "Enter SSH username: " REMOTE_USER
fi
if [[ -n "$2" ]]; then
REMOTE_HOST="$2"
else
read -rp "Enter Remote Host (IP/Domain): " REMOTE_HOST
fi
if [[ -n "$3" ]]; then
REMOTE_DIR="$3"
else
read -rp "Enter Remote Directory Path: " REMOTE_DIR
fi
# Validate input
if [[ -z "$REMOTE_USER" || -z "$REMOTE_HOST" || -z "$REMOTE_DIR" ]]; then
echo "Error: All parameters (REMOTE_USER, REMOTE_HOST, REMOTE_DIR) are required!"
exit 1
fi
# List files on the remote machine
echo "Fetching file list from ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}..."
FILES=$(ssh "${REMOTE_USER}@${REMOTE_HOST}" "ls -p ${REMOTE_DIR} | grep -v /")
if [[ -z "$FILES" ]]; then
echo "No files found in the remote directory!"
exit 1
fi
# Display file list with numbers
echo "Available files:"
IFS=$'\n' FILE_ARRAY=($FILES)
for i in "${!FILE_ARRAY[@]}"; do
echo "$((i+1))). ${FILE_ARRAY[$i]}"
done
# Ask user to choose files
echo "Enter the numbers of the files you want to download (comma-separated, e.g., 1,3,5):"
read -r SELECTION
# Parse selection
IFS=',' read -r -a SELECTED_INDICES <<< "$SELECTION"
SELECTED_FILES=()
for index in "${SELECTED_INDICES[@]}"; do
if [[ "$index" =~ ^[0-9]+$ ]] && (( index > 0 && index <= ${#FILE_ARRAY[@]} )); then
SELECTED_FILES+=("${FILE_ARRAY[$((index-1))]}")
else
echo "Invalid selection: $index"
fi
done
# Download selected files using SCP
if [[ ${#SELECTED_FILES[@]} -eq 0 ]]; then
echo "No valid files selected. Exiting."
exit 1
fi
echo "Downloading selected files..."
for FILE in "${SELECTED_FILES[@]}"; do
scp "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/${FILE}" .
done
echo "Download completed!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment