Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
On this page

Configuring the rollback_hosts_linux.sh Script

Updated on 2024-12-20 GMT+08:00

Modify the configuration in the example script to meet your specific requirements.

Prerequisites

You have completed all preparations.

Procedure

  1. Create a file named rollback_hosts_linux.sh on the server where the script is executed, and copy the following script content to the file. If you have connected to the Linux source servers through SSH, you can directly use Vim to create and edit a script file. The procedure is as follows:

    1. In the Vim editor, press I to enter insert mode.
    2. Copy and paste the following script code and press Esc.
    3. Run :wq to save and exit.
    #!/bin/bash
     
    # Configuration
     
    # Log directory path: Used to store run logs, error logs, and summary logs.
    # If the directory doesn't exist, the script will create it automatically.
    LOG_DIR="/var/log/update_hosts"
     
    # Run log file path: Records detailed information about the script's execution.
    RUN_LOG="$LOG_DIR/run.log"
     
    # Error log file path: Records any errors that occur during the script's execution.
    ERROR_LOG="$LOG_DIR/error.log"
     
    # Summary log file path: Records a summary of the script's execution, including the number of successful and failed servers.
    SUMMARY_LOG="$LOG_DIR/summary.log"
     
    # CSV file path: Contains information about the target hosts (must be manually created and configured).
    CSV_FILE="target_servers.csv"
    DEFAULT_PORT=22
    SSH_TIMEOUT=10
     
    # Initialize log directory and files
    initialize_logs() {
        mkdir -p "$LOG_DIR"
        echo "========================================" >> "$RUN_LOG"
        echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - Starting new rollback execution" >> "$RUN_LOG"
        echo "========================================" >> "$RUN_LOG"
     
        echo "========================================" >> "$ERROR_LOG"
        echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - Starting new rollback execution" >> "$ERROR_LOG"
        echo "========================================" >> "$ERROR_LOG"
     
        echo "========================================" > "$SUMMARY_LOG"
        echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - Starting new rollback execution" >> "$SUMMARY_LOG"
        echo "========================================" >> "$SUMMARY_LOG"
    }
     
    # Log info function
    log_info() {
        echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$RUN_LOG"
    }
     
    # Log error function
    log_error() {
        echo "[ERROR] $(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$RUN_LOG" "$ERROR_LOG"
    }
     
    # Read server information from CSV file
    read_servers_from_csv() {
        local csv_file="$1"
        local servers=()
        local header_skipped=false
     
        if [ ! -f "$csv_file" ]; then
            log_error "CSV file '$csv_file' not found."
            exit 1
        fi
     
        # Ensure file ends with a newline character
        sed -i -e '$a\' "$csv_file"
     
        while IFS=, read -r username ip port password; do
            # Skip header row
            if [ "$header_skipped" = false ]; then
                header_skipped=true
                continue
            fi
            # Skip empty and invalid rows
            if [[ -z "$username" || -z "$ip" ]]; then
                continue
            fi
            port=${port:-$DEFAULT_PORT} # Use default port 22
            # Ensure port is numeric
            if ! [[ "$port" =~ ^[0-9]+$ ]]; then
                log_error "Invalid port '$port' for $username@$ip. Skipping this server."
                continue
            fi
            servers+=("$username@$ip:$port:$password")
        done < "$csv_file"
     
        echo "${servers[@]}"
    }
     
    # Initialize log files
    initialize_logs
     
    # Read server information from CSV file
    servers=($(read_servers_from_csv "$CSV_FILE"))
     
    # Counters for success and failure
    success_count=0
    failure_count=0
    failed_servers=()
     
    # Iterate over each server and execute rollback
    for server in "${servers[@]}"; do
      # Extract user, IP, port, and password information
      IFS=':' read -r user_host port pass <<< "$server"
      IFS='@' read -r user ip <<< "$user_host"
      
      log_info "Starting rollback for $user@$ip:$port"
     
      # Create temporary script and SSH_ASKPASS script
      tmp_script=$(mktemp)
      askpass_script=$(mktemp)
     
      cat <<EOF > "$tmp_script"
    #!/bin/bash
    # Backup hosts file
    if [ ! -f /etc/hosts.bak ]; then
      cp /etc/hosts /etc/hosts.bak
    fi
     
    # Remove old Migration-proxy section
    sed -i '/#Migration-proxy-start/,/#Migration-proxy-end/d' /etc/hosts
    EOF
     
      cat <<EOF > "$askpass_script"
    #!/bin/bash
    echo "$pass"
    EOF
     
      chmod +x "$tmp_script" "$askpass_script"
     
      # Set SSH_ASKPASS environment variable and use ssh to connect to the target machine and execute the temporary script
      export SSH_ASKPASS="$askpass_script"
      export DISPLAY=:0
     
      ssh_output=$(mktemp)
      setsid ssh -o BatchMode=no -o ConnectTimeout=$SSH_TIMEOUT -o StrictHostKeyChecking=no -p "$port" "$user@$ip" 'bash -s' < "$tmp_script" 2> "$ssh_output"
      ssh_status=$?
     
      if [ $ssh_status -eq 0 ]; then
        log_info "Rolled back hosts on $ip:$port successfully"
        ((success_count++))
      else
        ssh_error=$(cat "$ssh_output")
        case $ssh_status in
          1)
            log_error "General error occurred while rolling back hosts on $ip:$port: $ssh_error"
            ;;
          2)
            log_error "Misuse of shell builtins while rolling back hosts on $ip:$port: $ssh_error"
            ;;
          255)
            if [[ "$ssh_error" == *"Permission denied"* ]]; then
              log_error "SSH login failed for $user@$ip:$port: Permission denied (password may be incorrect or username is wrong)"
            elif [[ "$ssh_error" == *"Connection refused"* ]]; then
              log_error "SSH login failed for $user@$ip:$port: Connection refused (port may be incorrect or SSH service not running on target)"
            elif [[ "$ssh_error" == *"No route to host"* ]]; then
              log_error "SSH login failed for $user@$ip:$port: No route to host (network unreachable)"
            elif [[ "$ssh_error" == *"Host key verification failed"* ]]; then
              log_error "SSH login failed for $user@$ip:$port: Host key verification failed"
            elif [[ "$ssh_error" == *"Connection timed out"* ]]; then
              log_error "SSH login failed for $user@$ip:$port: Connection timed out"
            else
              log_error "SSH login failed for $user@$ip:$port: $ssh_error"
            fi
            ;;
          *)
            log_error "An unknown error occurred while rolling back hosts on $ip:$port: $ssh_error"
            ;;
        esac
        failed_servers+=("$user@$ip:$port")
        ((failure_count++))
      fi
     
      # Remove temporary scripts and SSH output file
      rm -f "$tmp_script" "$askpass_script" "$ssh_output"
    done
     
    # Calculate failure and success percentages
    total_count=${#servers[@]}
    failure_percentage=$(echo "scale=2; ($failure_count / $total_count) * 100" | bc)
    success_percentage=$(echo "scale=2; ($success_count / $total_count) * 100" | bc)
     
    # Output summary result and log to file
    summary_content=$(cat <<EOF
    ========================================
    [SUMMARY] $(date '+%Y-%m-%d %H:%M:%S') - Execution Rollback Summary
    ========================================
    Total number of servers: $total_count
    Number of successful rollbacks: $success_count
    Number of failed rollbacks: $failure_count
    Success rate: $success_percentage%
    Failure rate: $failure_percentage%
    ----------------------------------------
    EOF
    )
     
    if [ $failure_count -gt 0 ]; then
        summary_content+="Failed servers:\n"
        for server in "${failed_servers[@]}"; do
            summary_content+="  - $server\n"
        done
    fi
    summary_content+="========================================"
     
    # Output summary result to log file and terminal
    echo -e "$summary_content" | tee -a "$SUMMARY_LOG"
     
    log_info "Script execution completed. Check $SUMMARY_LOG for summary."

  2. Modify the following parameters in the script to meet your needs:

    • LOG_DIR="/var/log/rollback_hosts"
      • Description: log directory
      • Default value: /var/log/rollback_hosts
      • Suggestion: Change the value to a directory for which the current user has the write permission.
      • Example: LOG_DIR="/home/username/rollback_hosts_logs"
    • CSV_FILE="target_servers.csv"
      • Description: CSV file path. The file contains the source server information.
      • Default value: target_servers.csv
      • Suggestion: Use an absolute path or a correct relative path.
      • Example: CSV_FILE="/home/username/configs/servers.csv"

  3. Saving the changes. Run the script in a terminal window. If a GUI is available, press Ctrl+Alt+T to open the terminal.

    ./rollback_hosts_linux.sh

    The script will output log information in the terminal window and generate a result report upon completion. You can view this report in the summary.log file in the directory specified by LOG_DIR.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback