如何编写清理无效应用链接脚本

wen 实用脚本 3

本文目录导读:

如何编写清理无效应用链接脚本

  1. 基础版本(Shell脚本)
  2. 使用说明
  3. 功能特点
  4. 高级用法

我来为您编写一个清理无效应用链接的脚本,以下是一个通用的Shell脚本,支持多种场景:

基础版本(Shell脚本)

#!/bin/bash
# 清理无效应用链接脚本
# 适用于Linux/Mac系统
# 配置文件
CONFIG_FILE="app_links.txt"
LOG_FILE="cleanup_$(date +%Y%m%d_%H%M%S).log"
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# 日志函数
log() {
    echo -e "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
# 检查URL是否有效
check_url() {
    local url=$1
    # 使用curl检查链接状态,-I只获取头部,-s静默模式,-L跟随重定向
    local http_code=$(curl -I -s -L -o /dev/null -w "%{http_code}" --connect-timeout 10 "$url" 2>/dev/null)
    if [[ $http_code -eq 200 ]] || [[ $http_code -eq 301 ]] || [[ $http_code -eq 302 ]]; then
        return 0  # 有效链接
    else
        return 1  # 无效链接
    fi
}
# 清理链接文件
cleanup_links() {
    local input_file=$1
    local output_file="${input_file%.*}_cleaned.txt"
    local temp_file=$(mktemp)
    log "开始清理链接文件: $input_file"
    # 统计
    local total=0
    local valid=0
    local invalid=0
    while IFS= read -r line; do
        # 跳过空行和注释
        [[ -z "$line" || "$line" =~ ^# ]] && continue
        total=$((total + 1))
        # 提取URL(假设每行一个URL)
        url=$(echo "$line" | grep -oP 'https?://[^\s]+' || echo "$line")
        log "${YELLOW}检查[$total]: $url${NC}"
        if check_url "$url"; then
            echo "$line" >> "$temp_file"
            valid=$((valid + 1))
            log "${GREEN}有效: $url${NC}"
        else
            invalid=$((invalid + 1))
            log "${RED}无效: $url${NC}"
        fi
        # 添加延迟,避免请求过快
        sleep 0.5
    done < "$input_file"
    # 生成清理后的文件
    if [[ -s "$temp_file" ]]; then
        mv "$temp_file" "$output_file"
        log "已生成清理后的文件: $output_file"
    else
        rm "$temp_file"
        log "所有链接都无效,未生成清理文件"
    fi
    # 输出统计信息
    log "==================================="
    log "统计信息:"
    log "总链接数: $total"
    log "有效链接: $valid"
    log "无效链接: $invalid"
    log "==================================="
}
# 批量清理模式(并行检查)
batch_cleanup() {
    local input_file=$1
    local output_file="${input_file%.*}_cleaned.txt"
    local temp_dir=$(mktemp -d)
    log "开始批量清理(并行模式)..."
    # 使用多进程检查
    while IFS= read -r line; do
        [[ -z "$line" || "$line" =~ ^# ]] && continue
        url=$(echo "$line" | grep -oP 'https?://[^\s]+' || echo "$line")
        echo "$url" >> "$temp_dir/urls.txt"
        echo "$line" >> "$temp_dir/original.txt"
    done < "$input_file"
    # 并行检查
    cat "$temp_dir/urls.txt" | while read -r url; do
        if check_url "$url"; then
            echo "$line" >> "$output_file"
        fi
    done
    rm -rf "$temp_dir"
}
# Python版本(更强功能)
python_cleanup() {
    cat > /tmp/cleanup_links.py << 'EOF'
#!/usr/bin/env python3
import requests
import concurrent.futures
import sys
import os
from urllib.parse import urlparse
def check_url(url, timeout=10):
    """检查URL是否有效"""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
        response = requests.head(url, timeout=timeout, headers=headers, allow_redirects=True)
        return response.status_code in [200, 301, 302, 303, 307, 308]
    except requests.exceptions.RequestException:
        return False
def cleanup_links_file(input_file, output_file, max_workers=10):
    """清理链接文件"""
    valid_links = []
    invalid_links = []
    # 读取链接
    with open(input_file, 'r') as f:
        links = [line.strip() for line in f if line.strip() and not line.startswith('#')]
    print(f"总共发现 {len(links)} 个链接")
    # 使用线程池并行检查
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        future_to_url = {executor.submit(check_url, url): url for url in links}
        for i, future in enumerate(concurrent.futures.as_completed(future_to_url), 1):
            url = future_to_url[future]
            try:
                is_valid = future.result()
                if is_valid:
                    valid_links.append(url)
                    print(f"[{i}/{len(links)}] ✓ 有效: {url}")
                else:
                    invalid_links.append(url)
                    print(f"[{i}/{len(links)}] ✗ 无效: {url}")
            except Exception as e:
                invalid_links.append(url)
                print(f"[{i}/{len(links)}] ✗ 错误: {url} - {str(e)}")
    # 保存有效链接
    with open(output_file, 'w') as f:
        for link in valid_links:
            f.write(link + '\n')
    # 输出统计
    print(f"\n{'='*40}")
    print(f"清理完成!")
    print(f"有效链接: {len(valid_links)}")
    print(f"无效链接: {len(invalid_links)}")
    print(f"已保存到: {output_file}")
    print(f"{'='*40}")
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("使用方法: python3 cleanup_links.py <input_file> [output_file]")
        sys.exit(1)
    input_file = sys.argv[1]
    output_file = sys.argv[2] if len(sys.argv) > 2 else "cleaned_links.txt"
    if not os.path.exists(input_file):
        print(f"错误: 文件 {input_file} 不存在")
        sys.exit(1)
    cleanup_links_file(input_file, output_file)
EOF
    python3 /tmp/cleanup_links.py "$1" "$2"
}
# 主菜单
main() {
    echo "=================================="
    echo "   无效应用链接清理工具 v1.0"
    echo "=================================="
    echo "1. 基础模式 (Shell, 单线程)"
    echo "2. 批量模式 (Shell, 并行)"
    echo "3. Python模式 (高速, 多线程)"
    echo "4. 退出"
    echo "=================================="
    read -p "请选择模式 [1-4]: " choice
    if [[ "$choice" == "4" ]]; then
        exit 0
    fi
    read -p "请输入链接文件路径: " file_path
    if [[ ! -f "$file_path" ]]; then
        echo "错误: 文件不存在"
        exit 1
    fi
    case $choice in
        1) cleanup_links "$file_path" ;;
        2) batch_cleanup "$file_path" ;;
        3) python_cleanup "$file_path" ;;
        *) echo "无效选择" ;;
    esac
}
# 运行主程序
main "$@"

使用说明

准备链接文件

创建一个包含链接的文本文件(每行一个):

https://www.example.com/app1
https://www.example.com/app2
https://www.example.com/app3

运行脚本

# 添加执行权限
chmod +x cleanup_links.sh
# 运行
./cleanup_links.sh

直接使用Python版本(推荐)

# 安装依赖
pip install requests
# 直接运行
python3 /tmp/cleanup_links.py input_links.txt output_links.txt
# 或者使用多线程(更快)
python3 /tmp/cleanup_links.py input_links.txt cleaned_links.txt

Windows PowerShell版本

# check_links.ps1
param(
    [Parameter(Mandatory=$true)]
    [string]$InputFile,
    [string]$OutputFile = "cleaned_links.txt"
)
function Check-Url {
    param($Url)
    try {
        $request = [System.Net.WebRequest]::Create($Url)
        $request.Method = "HEAD"
        $request.Timeout = 10000
        $response = $request.GetResponse()
        $statusCode = [int]$response.StatusCode
        $response.Close()
        return $statusCode -in @(200, 301, 302)
    } catch {
        return $false
    }
}
# 读取链接
$links = Get-Content $InputFile | Where-Object { $_ -and $_ -notmatch '^#' }
Write-Host "总共发现 $($links.Count) 个链接" -ForegroundColor Yellow
$validLinks = @()
$invalidLinks = @()
foreach ($url in $links) {
    Write-Host "检查: $url" -NoNewline
    if (Check-Url $url) {
        Write-Host " ✓ 有效" -ForegroundColor Green
        $validLinks += $url
    } else {
        Write-Host " ✗ 无效" -ForegroundColor Red
        $invalidLinks += $url
    }
}
# 保存有效链接
$validLinks | Out-File -FilePath $OutputFile
Write-Host "`n清理完成!" -ForegroundColor Green
Write-Host "有效链接: $($validLinks.Count)"
Write-Host "无效链接: $($invalidLinks.Count)"
Write-Host "已保存到: $OutputFile"
# 运行命令
# .\check_links.ps1 -InputFile "links.txt" -OutputFile "cleaned.txt"

功能特点

  1. 多种检查方式:支持HTTP状态码检查和超时处理
  2. 并行处理:Python版本使用多线程提高效率
  3. 日志记录:记录所有检查结果
  4. 统计信息:显示有效/无效链接数量
  5. 跨平台:支持Linux、Mac和Windows

高级用法

# 自定义检查(Python)
def custom_check_url(url):
    """自定义检查逻辑"""
    import json
    import requests
    try:
        # 模拟真实用户访问
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept': 'application/json,text/html,application/xhtml+xml'
        }
        # 检查页面内容
        response = requests.get(url, headers=headers, timeout=15)
        if response.status_code == 200:
            # 检查是否包含特定内容
            if "404" in response.text or "not found" in response.text.lower():
                return False
            return True
        return False
    except:
        return False

选择适合您的版本和模式运行即可,如果需要其他功能或修改,请告诉我。

抱歉,评论功能暂时关闭!