安装 Python 3.8+ 版本,验证命令:python --version 或 python3 --version
确保 pip 工具可用:pip --version 或 pip3 --version
① 打开 cmd 命令提示符,执行安装命令:
pip install locust
② 验证安装成功:
locust -V
③ 若出现依赖报错,升级 pip 后重试:
python -m pip install --upgrade pip
① 更新系统包索引:
sudo apt update
② 安装 Python 和 pip(若未安装):
sudo apt install python3 python3-pip -y
③ 安装 Locust:
pip3 install locust
④ 验证安装:
locust -V
创建 Python 脚本,定义用户行为:
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 3) # 任务间隔 1-3 秒
@task
def index_page(self):
self.client.get("/") # 访问首页
@task(3) # 权重为3,执行频率更高
def about_page(self):
self.client.get("/about") # 访问关于页
① 进入脚本所在目录,执行启动命令:
locust -f test_locust.py --host=https://目标网站.com
② 打开浏览器访问:http://localhost:8089
✓ Number of users:总并发用户数
✓ Spawn rate:每秒启动的用户数
✓ Host:目标网站地址(若启动时已指定可忽略)
点击 Start swarming 开始压测
import csv
from locust import HttpUser, task, between
def get_test_data():
data = []
with open("test_data.csv", newline="") as f:
reader = csv.reader(f)
next(reader) # 跳过表头
for row in reader:
data.append({"username": row[0], "password": row[1]})
return data
test_data = get_test_data()
class UserBehavior(HttpUser):
wait_time = between(1, 2)
@task
def login(self):
for data in test_data:
self.client.post("/login", data=data)
Windows/Kali 主控机:
locust -f test_locust.py --host=https://目标网站.com --master
Windows/Kali 从机:
locust -f test_locust.py --slave --master-host=主控机IP
locust -f test_locust.py --host=https://目标网站.com --headless -u 100 -r 10 -t 5m --html=report.html
参数说明:--headless无界面模式,-u用户数,-r每秒启动数,-t压测时长
仅能对自己拥有权限的网站/服务器进行压测,未经授权测试他人网站属于违法行为,需承担法律责任
Windows:打开任务管理器,监控 CPU、内存、网络占用率
Kali:使用 top 或 htop 命令实时监控系统资源
① 报错 Address already in use:端口 8089 被占用,指定新端口启动:locust -f test.py --port=8090
② 报错 No module named locust:环境变量未配置,使用 python -m locust 启动