xiao9469 发表于 2025-10-27 22:18:06

关于代理采集怎样才能有效防范策略~!

由于现在都TMD不仅仅是使用机房IP代理了,基本都是使用的家用宽带代理,这种想通过IP来实现屏蔽是很困难的,那么如何能有效解决这个问题。
百度推出了百度智能风控系统,那么我们对接他这个系统对访问的IP进行筛查,如果IP存在行为风险那么就禁止访问。
PS:百度智能风控是否收费不清楚,我都是没注册登录,免费查询的IP,但是每天有限制次数,那么估计应该是收费的。
功能:
✅ 自动获取客户端真实IP ✅ 调用百度智能云IP风险查询API ✅ 根据风险等级阻止高风险IP ✅ 24小时内阻止重复访问 ✅ 白名单机制 ✅ 错误处理和日志记录 ✅ 自动清理过期阻止记录

如下为PHP代码,仅做参考!
如需全局保护需按照所需修改!
东西是死的,人是活的,代码不重要,重要的是我想给大家提供一个思路而已!
<?php
/**
* 基于百度智能云IP行为风险查询的访问控制系统
* 检测到高风险IP则阻止当日访问
*/

class IPRiskControl {
    private $baidu_api_url = 'https://api.baidu.com/iprisk/v1/query'; // 百度智能云IP风险查询API地址
    private $access_token = 'YOUR_BAIDU_ACCESS_TOKEN'; // 百度智能云访问令牌
    private $blocked_ips_file = 'blocked_ips.json'; // 被阻止IP记录文件
    private $cache_time = 86400; // 缓存时间24小时

    public function __construct($access_token = null) {
      if ($access_token) {
            $this->access_token = $access_token;
      }
    }

    /**
   * 获取客户端真实IP
   */
    private function getClientIP() {
      $ip = '';
      if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
      } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
      } else {
            $ip = $_SERVER['REMOTE_ADDR'];
      }

      // 处理多个IP的情况(如经过代理)
      $ips = explode(',', $ip);
      return trim($ips);
    }

    /**
   * 调用百度智能云IP风险查询API
   */
    private function queryIPRisk($ip) {
      $url = $this->baidu_api_url;

      $data = [
            'ip' => $ip,
            'access_token' => $this->access_token
      ];

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_TIMEOUT, 10);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

      $response = curl_exec($ch);
      $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      curl_close($ch);

      if ($http_code !== 200) {
            error_log("百度API请求失败,HTTP代码: $http_code");
            return null;
      }

      $result = json_decode($response, true);
      if (json_last_error() !== JSON_ERROR_NONE) {
            error_log("JSON解析失败: " . json_last_error_msg());
            return null;
      }

      return $result;
    }

    /**
   * 读取被阻止的IP记录
   */
    private function readBlockedIPs() {
      if (!file_exists($this->blocked_ips_file)) {
            return [];
      }

      $content = file_get_contents($this->blocked_ips_file);
      $data = json_decode($content, true);

      if (json_last_error() !== JSON_ERROR_NONE) {
            return [];
      }

      // 清理过期的记录
      $current_time = time();
      $cleaned_data = [];
      foreach ($data as $ip => $block_time) {
            if ($current_time - $block_time < $this->cache_time) {
                $cleaned_data[$ip] = $block_time;
            }
      }

      // 如果清理后有变化,更新文件
      if (count($cleaned_data) !== count($data)) {
            $this->saveBlockedIPs($cleaned_data);
      }

      return $cleaned_data;
    }

    /**
   * 保存被阻止的IP记录
   */
    private function saveBlockedIPs($blocked_ips) {
      file_put_contents($this->blocked_ips_file, json_encode($blocked_ips, JSON_PRETTY_PRINT));
    }

    /**
   * 检查IP是否已被阻止
   */
    private function isIPBlocked($ip) {
      $blocked_ips = $this->readBlockedIPs();
      return isset($blocked_ips[$ip]);
    }

    /**
   * 阻止IP访问
   */
    private function blockIP($ip) {
      $blocked_ips = $this->readBlockedIPs();
      $blocked_ips[$ip] = time();
      $this->saveBlockedIPs($blocked_ips);
    }

    /**
   * 判断是否为高风险IP
   */
    private function isHighRiskIP($api_result) {
      // 根据百度API返回结果判断风险等级
      // 这里需要根据百度智能云API的实际返回字段进行调整

      if (!isset($api_result['data']['risk_level'])) {
            return false;
      }

      $risk_level = $api_result['data']['risk_level'];

      // 假设风险等级:1-低风险,2-中风险,3-高风险
      // 具体等级定义请参考百度智能云文档
      return $risk_level >= 3;
    }

    /**
   * 主检查函数
   */
    public function checkAccess() {
      $client_ip = $this->getClientIP();

      // 检查IP是否在白名单中(可选)
      if ($this->isWhitelistIP($client_ip)) {
            return true;
      }

      // 检查IP是否已被阻止
      if ($this->isIPBlocked($client_ip)) {
            $this->denyAccess("您的IP已被暂时阻止访问");
            return false;
      }

      // 查询IP风险
      $risk_result = $this->queryIPRisk($client_ip);

      if ($risk_result === null) {
            // API查询失败时,可以选择放行或阻止
            // 这里选择放行,避免影响正常用户
            return true;
      }

      // 判断是否为高风险IP
      if ($this->isHighRiskIP($risk_result)) {
            $this->blockIP($client_ip);
            $this->denyAccess("检测到访问风险,您的IP已被暂时阻止");
            return false;
      }

      return true;
    }

    /**
   * 白名单IP检查(可选)
   */
    private function isWhitelistIP($ip) {
      $whitelist = [
            '127.0.0.1',
            '192.168.1.1',
            // 添加其他可信IP
      ];

      return in_array($ip, $whitelist);
    }

    /**
   * 拒绝访问处理
   */
    private function denyAccess($message = '') {
      http_response_code(403);
      echo "<!DOCTYPE html>
      <html>
      <head>
            <title>访问被拒绝</title>
            <style>
                body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
                .error { color: #d63031; background: #ffeaa7; padding: 20px; border-radius: 5px; }
            </style>
      </head>
      <body>
            <div class='error'>
                <h1>访问被拒绝</h1>
                <p>$message</p>
                <p>如有疑问,请联系网站管理员。</p>
            </div>
      </body>
      </html>";
      exit;
    }
}

// 使用示例
try {
    // 初始化IP风险控制系统
    $ip_control = new IPRiskControl('你的百度智能云AccessToken');

    // 检查访问权限
    if (!$ip_control->checkAccess()) {
      // 访问被阻止,脚本已退出
      exit;
    }

    // 正常业务逻辑继续执行
    // echo "欢迎访问我们的网站!";

} catch (Exception $e) {
    // 错误处理
    error_log("IP风险控制系统错误: " . $e->getMessage());
    // 发生错误时可以选择继续执行或阻止访问
}

// 正常业务代码放在这里...(当然也可以修改成代码引入的形式,东西是死的,人是活的,代码不重要,重要的是我想给大家提供一个思路而已!)
?>
页: [1]
查看完整版本: 关于代理采集怎样才能有效防范策略~!