【问题标题】:Converting a CURL into python script将 CURL 转换为 python 脚本
【发布时间】:2020-04-19 17:40:29
【问题描述】:

我正在尝试将 Curl POST 请求转换为 python 脚本,但我没有得到所需的输出,请让我知道我在这里做错了什么。

CURL request
 curl -s -w '%{time_starttransfer}\n' --request POST \
       --url http://localhost:81/kris/execute \
       --header 'content-type: application/json' \
       --data '{"command":["uptime"], "iplist":["10.0.0.1"], "sudo":true}'

这会在为其提供 ip 的节点中运行 uptime 命令并返回 JSON 输出:

{"command":"uptime","output":["{\"body\":\" 17:30:06 up 60 days, 11:23,  1 user,  load average: 0.00, 0.01, 0.05\\n\",\"host\":\"10.0.0.1\"}"]}0.668894

当我尝试用 python 运行相同的东西时,它会失败并且永远不会得到输出

代码:

import urllib3
import json

http = urllib3.PoolManager()

payload = '{"command":["uptime"], "iplist":["10.0.0.1"], "sudo":true}'
encoded_data = json.dumps(payload)

resp = http.request(
     'POST',
     'http://localhost:81/kris/execute ',
     body=encoded_data,
     headers={'Content-Type': 'application/json'})
print(resp)

【问题讨论】:

    标签: python-3.x curl urllib3


    【解决方案1】:

    我建议您使用requests library。它比urllib 级别更高,使用更简单。 (有关它很棒的原因列表,请参阅this answer。)

    此外,它只需要对您的代码进行微小的更改即可工作:

    import requests
    
    payload = '{"command":["uptime"], "iplist":["10.0.0.1"], "sudo":true}'
    
    resp = requests.post(
         'http://localhost:81/kris/execute',
         data=payload,
         headers={'Content-Type': 'application/json'})
    print(resp.text)
    

    请注意,方法POST 是函数而不是参数,它使用命名参数data 而不是body。它还返回一个Response 对象,因此您必须访问其text 属性才能获取实际的响应内容。


    另外,您不需要json.dumps 您的字符串。该函数用于将 Python 对象转换为 JSON 字符串。您使用的字符串已经是有效的 JSON,所以您应该直接发送它。

    【讨论】:

    • 由于某种原因 json.dumps(payload) 给出了 Null 输出,当我通过更改来评论 encoded_data 时,效果很好。谢谢你。请求 > urllib {true} .
    • 哦,对了!无论如何它应该可以工作,但是这里实际上不需要调用json.dumps。我更新了答案以解释这一点。
    【解决方案2】:

    这是一个在线实用程序,您可以查看将 curl 请求转换为 python 代码。

    Curl to python converter

    另一种选择是 Postman 应用程序。在代码部分,您可以选择将 curls 转换为各种语言的代码。

    通过在 postman 中运行 curl 来检查 api 请求是否正常工作是一个很好的做法。

    对于您的情况,这里是使用 python 请求库的代码。

        import requests
    
    headers = {
        'content-type': 'application/json',
    }
    
    data = '{"command":["uptime"], "iplist":["10.0.0.1"], "sudo":true}'
    
    response = requests.post('http://localhost:81/kris/execute', headers=headers, data=data)
    

    希望对您有所帮助!快乐编码!

    【讨论】:

    • 你的链接好像没有网址,只有参数
    • @CycleOfTheAbsurd 哦,是的......现在修复它..ty!
    猜你喜欢
    • 2020-06-10
    • 2011-05-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2018-05-14
    • 1970-01-01
    相关资源
    最近更新 更多