Postman - 我如何调用一个shell脚本并将其赋值给一个变量?

4

我有一个简单的shell脚本,希望在后台运行并将其分配给Postman全局变量。有任何关于如何在Postman中实现此目标的想法吗?

2个回答

4

通过外部脚本设置动态变量

Postman只能触发HTTP请求,因此我们没有直接执行例如.sh脚本的方法。 但是,您可以运行一个本地服务器(这里使用node js服务器),并编写一个node js脚本来执行shell脚本或其他可执行文件。 现在让我们逐步进行:

第1步:定义任务

我有一个PHP脚本,它提供了令牌。此令牌将在API请求中使用。该脚本看起来像下面这样,并保存为TokenGenerator.php

<?php
require "vendor/autoload.php";

class TokenGeneration {

    public  $appID= "50A454F3-EE11-4A4C-B708-965BC7640C08";
    public $token = NULL; 

    public function __construct(){
        //echo "\n URL: ".$this->url;
        $this->token = $this->generateAppToken();
    }

    function generateAppToken(){
        $message =   $this->appID."~REQUEST".time();
        //echo "\n message: ".$message;

        $cryptor = new \RNCryptor\RNCryptor\Encryptor;
        $base64Encrypted = $cryptor->encrypt($message, $this->appID);
        //echo "\n token: ". $base64Encrypted;
        return $base64Encrypted;
    }
}
?>

步骤 2:获取你的令牌

我们将编写 token.php 程序从 TokenGenerato.php 获取令牌。

<?php
  require "TokenGeneration.php";
  $tokengen = new TokenGeneration();
  echo $tokengen->token;
?>

我们可以通过以下方式运行此php脚本:

php token.php

输出结果:

AwFmHNkA1HdM1VHFadu89nE3xZuKO3pLQ7cHOrCj2x2WZoSt

步骤三:创建Node.js脚本。

您可以使用child_process模块在Node.js中执行shell命令。 child_process教程

token.js 中创建以下代码的Node.js脚本:

const http = require('http'), { exec } = require('child_process');

http.createServer((req, res) => {
  // Give the path of your bat or exe file
  exec('php token.php', (err, stdout, stderr) => {
    console.log({ err, stdout, stderr });

    if (err) {
      return res.writeHead(500).end(JSON.stringify(err));
    }

    // Output of the script in stdout
    return res.writeHead(200).end(stdout);
  });
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

接下来,使用以下命令启动Node服务器。

node token.js

步骤4:Postman的预请求脚本。

首先,在Postman中创建新的API请求,然后选择Pre-request Script并编写以下代码,在实际API调用发生之前发送http请求并将响应保存在本地变量中。

pm.variables.set("password", "AwErFEinDqiOvXFx2wVgHvt+Rpo0jdoTH0D0QldS");

console.log("password: ", pm.variables.get("password"));

pm.sendRequest('http://127.0.0.1:8000', (err, response) => {
    // This will have the output of your batch file
    console.log(response.text());
    pm.variables.set("token", response.text());
})

最后,准备使用令牌的标头

令牌 = {{token}}


0

不要使用全局变量,而是使用环境变量。

在Postman中,环境可以导入/导出为简单的JSON文件,这些文件可以轻松地通过外部脚本进行修改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接