编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

屏蔽疯狂蜘蛛,防止CPU占用100%

wxchong 2025-01-16 21:14:38 开源技术 23 ℃ 0 评论

站点总是某个时间段莫名的cpu100%,资源占用也不高,这就有必要怀疑爬虫问题。

1. 使用"robots.txt"规范

在网站根目录新建空白文件,命名为"robots.txt",将下面内容保存即可。


User-agent: Baiduspider
Disallow:
User-agent: YisouSpider
Disallow:
User-agent: 360Spider
Disallow:
User-agent: Sosospider
Disallow:
User-agent: sogou spider
Disallow:
User-agent: YodaoBot
Disallow:
User-agent: Googlebot
Disallow:
User-agent: bingbot
Disallow:
User-agent: *
Disallow: /


2. 通过nginx

有些爬虫是不按规则出牌的,我们必须要能自己控制,将下面代码添加到"location / { }" 段里面,比如伪静态规则里面即可。


#禁止Scrapy等工具的抓取
if ($http_user_agent ~ (Scrapy|Curl|HttpClient)) {
return 403;
}

#禁止指定UA及UA为空的访问
if ($http_user_agent ~ "YandexBot|Bytespider|FeedDemon|Indy Library|Alexa Toolbar|AskTbFXTV|AhrefsBot|CrawlDaddy|CoolpadWebkit|Java|Feedly|UniversalFeedParser|ApacheBench|Microsoft URL Control|Swiftbot|ZmEu|oBot|jaunty|Python-urllib|lightDeckReports Bot|YYSpider|DigExt|HttpClient|MJ12bot|heritrix|Ezooms|^$" ) {
return 403;
}
#禁止非GET|HEAD|POST方式的抓取
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 403;
}


注意: ~ 为模糊匹配 ,~* 为 模糊匹配不区分大小写

测试一下:

curl -I -A "Mozilla/5.0 YandexBot demo" http://你的域名

返回 403 表示设置成功!

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表