在 CentOS 上使用 Postman 的脚本方式
在 CentOS 上,Postman 的“脚本”主要有两类:一类是在 Postman 应用内的 Pre-request Script 与 Tests(JavaScript),另一类是在服务器上用 Newman 执行集合的命令行脚本(Shell/Bash)。前者用于单接口调试与断言,后者用于批量、定时与 CI/CD 自动化。下面给出可直接复用的步骤与示例。
一 环境准备
sudo tar -xzf Postman-linux-x64-*.tar.gz -C /optsudo ln -s /opt/Postman/Postman /usr/bin/postmanpostmansudo yum install -y nodejs npmsudo npm install -g newman二 在 Postman 应用内使用脚本
pm.environment.set("timestampHeader", new Date().toISOString())
{{timestampHeader}}pm.test("Status code is 200", () => {
pm.response.to.have.status(200);
});
pm.test("Body matches string", () => {
pm.expect(pm.response.text()).to.include("成功");
});
pm.environment.set("api_key", "your_api_key"),在 URL/Header/Body 中以 {{api_key}} 引用三 使用 Newman 在 CentOS 上运行脚本
newman run collection.json -e environment.json
sudo npm install -g newman-reporter-htmlnewman run collection.json -e environment.json -r html --reporter-html-export report.html
#!/usr/bin/env bash
set -e
COLLECTION="/path/to/collection.json"
ENVIRONMENT="/path/to/environment.json"
REPORT="/path/to/report.html"
newman run "$COLLECTION" -e "$ENVIRONMENT" -r html --reporter-html-export "$REPORT"
chmod +x run_postman.sh
./run_postman.sh
[Unit]
Description=Newman Postman Collection Runner
After=network.target
[Service]
ExecStart=/usr/local/bin/newman run /path/to/collection.json -e /path/to/environment.json -r html --reporter-html-export /path/to/report.html
Restart=always
User=your_username
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now postman.service
sudo systemctl status postman.service
四 常见问题与实用建议
pm.environment.get/set 或 pm.iterationData.get 明确取值来源。git/制品库做历史留存与对比分析。