วัน: 12 กันยายน 2010

  • MacOs: Downloads จาก windows share folder

    เป็น script ที่ช่วยในการ Downloads จาก windows share folder หลาย ๆ ไฟล์ในโพลเดอร์และซับโพลเดอร์พร้อม ๆ กันในทีเดียว โดยจะข้ามไฟล์ที่ดาน์โหลดมาแล้ว จะข้ามไปให้เอง และรองรับทั้ง path windows ปกติ หรือ smb://


    macos_downloads_smb.sh

    #!/bin/bash
    
    clear
    
    # ==============================================================================
    # USAGE INSTRUCTIONS & DOCUMENTATION
    # ==============================================================================
    # Purpose: Automatically mounts a remote SMB share and downloads specified 
    #          directories to a local destination using rsync with deep auditing.
    #
    # How to use:
    # 1. Update the CONFIGURATION section below with your desired paths and SMB server details.
    # 2. In the 'paths' array, you can copy-paste either Windows or Mac paths.
    #    ⚠️ IMPORTANT: If a path contains backslashes (\) or spaces, you MUST enclose 
    #       it in SINGLE QUOTES ('...') to prevent Bash from misinterpreting them.
    # 3. Make the script executable: chmod +x download_smb.sh
    # 4. Run the script: ./download_smb.sh
    # ==============================================================================
    
    # ==========================================
    # CONFIGURATION & INFORMATION SECTION
    # ==========================================
    # 1. Local destination directory on your Mac
    DEST_BASE="/Users/common/Meetings"
    
    # 2. SMB Server connection details
    SMB_SERVER="windows.plusmagi.com"
    SMB_BASE="commmon_technical"
    
    # 3. List of target directories to download (Supports both Windows and Mac paths)
    paths=(
    	'importData',
        'event,
    	'HolidayCalendar'
    	'VDO Training\Day 1'
    	'VDO Training\Day 2'
    	"Front Office/"
    )
    # ==========================================
    
    # --- AUTOMATED EXECUTION BEGINS HERE ---
    
    # Counter variables for tracking folders
    TOTAL_FOLDERS=${#paths[@]}
    SUCCESS_COUNT=0
    SKIP_COUNT=0
    FAIL_COUNT=0
    
    # Counter variables for tracking cumulative file metrics across all jobs
    GRAND_TOTAL_FILES=0
    GRAND_DOWNLOADED_FILES=0
    GRAND_SKIPPED_FILES=0
    
    # Ensure base directory exists locally
    mkdir -p "$DEST_BASE"
    
    # Trigger macOS to network mount the target volume 
    echo "Connecting to the server..."
    open "smb://${SMB_SERVER}/${SMB_BASE}"
    
    echo "⏳ Please wait for the system to mount..."
    MOUNT_POINT="/Volumes/${SMB_BASE}"
    counter=0
    
    # Keep polling until target volume is found in OS mounts (Timeout after 30s)
    while [ ! -d "$MOUNT_POINT" ]; do
    	sleep 2
    	counter=$((counter+2))
    	if [ $counter -gt 30 ]; then
    		echo "❌ Error: Cannot detect the target volume."
    		exit 1
    	fi
    done
    
    # Normalization function to standardize slashed syntax profiles
    convert_path() {
    	local input_path="$1"
    	# Replace all backslashes with standard unix slashes
    	local clean_path=$(echo "$input_path" | tr '\\' '/')
    	# Drop the server path dynamically if copied raw from Windows Explorer
    	clean_path=$(echo "$clean_path" | sed -E "s|//${SMB_SERVER}/${SMB_BASE}/||I")
    	clean_path=$(echo "$clean_path" | sed -E "s|^/||")
    	echo "$clean_path"
    }
    
    # Start auditing and processing folders sequentially
    for p in "${paths[@]}"; do
    	CLEANED_PATH=$(convert_path "$p")
    	SOURCE_DIR="$MOUNT_POINT/$CLEANED_PATH"
    	FOLDER_NAME=$(basename "$CLEANED_PATH")
    	TARGET_DIR="$DEST_BASE/$FOLDER_NAME"
    	
    	echo "----------------------------------------"
    	echo "🔄 Auditing Folder: $FOLDER_NAME"
    	echo "From: $SOURCE_DIR"
    	echo "To:   $TARGET_DIR"
    	
    	# 1. Verify existence of target directory profile on server
    	if [ ! -d "$SOURCE_DIR" ]; then
    		echo "❌ Status: Failed (Source directory not found on SMB)"
    		((FAIL_COUNT++))
    		continue
    	fi
    
    	mkdir -p "$TARGET_DIR"
    
    	# 2. Extract and layout the complete deep item payload tree structure
    	echo "📂 Comprehensive Content Tree on SMB:"
    	find "$SOURCE_DIR" ! -name ".DS_Store" -mindepth 1 2>/dev/null | sed "s|^$SOURCE_DIR/||" | sort | while read -r line; do
    		# Dynamically map formatting markers via path directory nesting depth
    		DEPTH=$(echo "$line" | tr -cd '/' | wc -c)
    		PREFIX=""
    		for ((i=0; i<DEPTH; i++)); do PREFIX="${PREFIX}  │"; done
    		NAME=$(basename "$line")
    		
    		if [ -d "$SOURCE_DIR/$line" ]; then
    			echo "$PREFIX  📁 $NAME/"
    		else
    			echo "$PREFIX  📄 $NAME"
    		fi
    	done
    
    	# 3. Pre-count total files on SMB (excluding .DS_Store and directories)
    	TOTAL_SMB_FILES=$(find "$SOURCE_DIR" -type f ! -name ".DS_Store" 2>/dev/null | wc -l | xargs)
    
    	# 4. Trigger raw processing sync and preserve modifications attributes
    	RSYNC_OUTPUT=$(rsync -rltvP --stats --exclude='.DS_Store' "$SOURCE_DIR/" "$TARGET_DIR/" 2>&1)
    	RSYNC_STATUS=$?
    
    	# 5. Safely extract network logs statistics
    	FILES_TRANSFERRED=$(echo "$RSYNC_OUTPUT" | grep "Number of regular files transferred:" | awk '{print $NF}')
    	if [ -z "$FILES_TRANSFERRED" ]; then FILES_TRANSFERRED=0; fi
    
    	SRC_TOTAL_SIZE=$(echo "$RSYNC_OUTPUT" | grep "Total file size:" | awk '{print $4}')
    	TARGET_TOTAL_FILES=$(find "$TARGET_DIR" -type f ! -name ".DS_Store" | wc -l | xargs)
    
    	# Calculate skipped files strictly based on total files vs transferred files
    	SKIPPED_FILES=$((TOTAL_SMB_FILES - FILES_TRANSFERRED))
    	if [ $SKIPPED_FILES -lt 0 ]; then SKIPPED_FILES=0; fi
    
    	# Accumulate grand total metrics across all items for the final audit report
    	GRAND_TOTAL_FILES=$((GRAND_TOTAL_FILES + TOTAL_SMB_FILES))
    	GRAND_DOWNLOADED_FILES=$((GRAND_DOWNLOADED_FILES + FILES_TRANSFERRED))
    	GRAND_SKIPPED_FILES=$((GRAND_SKIPPED_FILES + SKIPPED_FILES))
    
    	# 6. Strict Reporting Engine with Explicit File/Skip Counts
    	if [ $RSYNC_STATUS -ne 0 ]; then
    		echo "❌ Status: Failed (rsync exited with error code $RSYNC_STATUS)"
    		((FAIL_COUNT++))
    	elif [ "$FILES_TRANSFERRED" -gt 0 ]; then
    		echo "🚀 Status: Synced & Verified (Total files: $TOTAL_SMB_FILES | Downloaded: $FILES_TRANSFERRED | Skipped: $SKIPPED_FILES)"
    		echo "   [Integrity Check: Target now holds $TARGET_TOTAL_FILES files ($SRC_TOTAL_SIZE bytes)]"
    		((SUCCESS_COUNT++))
    	else
    		if [ "$TARGET_TOTAL_FILES" -gt 0 ]; then
    			echo "⏭️  Status: Skipped (Total files: $TOTAL_SMB_FILES | Downloaded: 0 | Skipped: $SKIPPED_FILES)"
    			((SKIP_COUNT++))
    		else
    			echo "⚠️ Warning: Skipped but Target directory appears to be empty!"
    			((SKIP_COUNT++))
    		fi
    	fi
    done
    
    # ==========================================
    # 📊 FINAL EXHAUSTIVE SUMMARY REPORT
    # ==========================================
    echo "========================================"
    echo "📊 EXHAUSTIVE DOWNLOAD SUMMARY REPORT"
    echo "========================================"
    echo "📁 Total Target Folders : $TOTAL_FOLDERS"
    echo "✅ Successfully Synced  : $SUCCESS_COUNT Folders"
    echo "⏭️  Skipped (Up to date) : $SKIP_COUNT Folders"
    if [ $FAIL_COUNT -gt 0 ]; then
    	echo "❌ Failed / Unverified  : $FAIL_COUNT Folders"
    fi
    echo "----------------------------------------"
    echo "📈 CUMULATIVE FILE AUDIT METRICS:"
    echo "📄 Grand Total Files    : $GRAND_TOTAL_FILES"
    echo "📥 Total Files Synced   : $GRAND_DOWNLOADED_FILES"
    echo "⏭️  Total Files Skipped  : $GRAND_SKIPPED_FILES"
    echo "========================================"
    if [ $FAIL_COUNT -eq 0 ]; then
    	echo "✅ Audit Pass: All folders and deep payloads verified successfully!"
    else
    	echo "⚠️ Audit Attention Required: Some sync paths threw validation errors."
    fi

    อ่านเพิ่มเติม