温馨提示×

怎样在linux跑postman脚本

小樊
39
2026-10-18 08:22:04
栏目: 智能运维

在 Linux 上运行 Postman 脚本(通常指 Postman 的 Collection 自动化测试),最常用、最推荐的方式是使用 Newman(Postman 官方命令行工具)。下面从「能不能直接跑」「标准做法」「示例」「常见场景」逐步说明。


一、先明确:Linux 上怎么“跑 Postman 脚本”

Postman 本身是一个 GUI 工具,Linux 服务器一般没有图形界面,所以:

✅ 正确做法:

  • 在 Windows / macOS 的 Postman 中 导出 Collection
  • 在 Linux 上使用 Newman 运行

❌ 不推荐:

  • 在 Linux 装桌面环境跑 Postman GUI(重、慢、不稳定)

二、安装 Newman(核心步骤)

1️⃣ 安装 Node.js(Newman 依赖)

# 以 Ubuntu 为例
sudo apt update
sudo apt install -y nodejs npm

node -v
npm -v

2️⃣ 安装 Newman

sudo npm install -g newman

验证:

newman --version

三、准备 Postman 脚本(Collection)

在 Postman 中:

  1. 写好请求 / 测试脚本(Tests 标签页)
  2. 导出 Collection:
    • Collection → Export
    • 选择 v2.1
    • 得到 xxx.json

(可选)导出环境变量:

  • Environments → Export

四、在 Linux 上运行 Collection

最简单运行

newman run xxx.json

使用环境变量

newman run xxx.json \
  -e env.json

常用参数

newman run xxx.json \
  -e env.json \
  --reporters cli,html \
  --reporter-html-export report.html \
  --timeout-request 10000

五、结合 Shell / CI(常用)

Shell 脚本

#!/bin/bash
newman run api_test.json -e prod.env.json || exit 1

Jenkins / GitLab CI

test:
  script:
    - npm install -g newman
    - newman run collection.json -e env.json

六、常见进阶需求

✅ 1. 参数化(数据驱动)

newman run api.json -d data.csv

data.csv 示例:

username,password
a,123
b,456

Collection 中用:

pm.iterationData.get("username")

✅ 2. 设置 base_url

环境变量:

{
  "base_url": "https://api.example.com"
}

请求 URL:

{{base_url}}/login

✅ 3. 断言示例(Tests)

pm.test("状态码 200", () => {
  pm.response.to.have.status(200);
});

七、如果你说的“Postman 脚本”是 JS 文件?

Postman 的 Tests / Pre-request 不能直接当 Node 脚本跑,它们依赖 Postman 运行时。

✅ 正确方式:

  • 写成 Collection
  • 用 Newman 跑

八、总结一句话

Linux 跑 Postman 脚本 = 导出 Collection + Newman 命令行运行

如果你愿意,可以告诉我:

  • 是接口测试?还是 CI 自动化?
  • 有没有环境变量 / 登录态?
  • 用的是 Ubuntu / CentOS / 容器?

我可以给你一份 可直接用的完整示例。

0 踩