在Python脚本中执行curl命令 [英] Execute curl command within a Python script

查看:6027
本文介绍了在Python脚本中执行curl命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在python脚本中执行curl命令。



如果我在终端中执行它,它看起来像这样:

  curl -X POST -d'{nw_src:10.0.0.1/32,nw_dst:10.0.0.2/32 nw_proto:ICMP,actions:ALLOW,priority:10}'http:// localhost:8080 / firewall / rules / 0000000000000001 
/ pre>

我已经看到使用 pycurl 的建议,但我不知道如何应用它

  subprocess.call [
'curl',
'-X',
'POST',
'-d',
flow_x,
'http:// localhost:8080 / firewall / rules / 0000000000000001'
])

有没有更好的方法?

解决方案

你可以使用urllib @roippi说:

  import urllib2 
data ='{nw_src:10.0.0.1/32,nw_dst:10.0.0.2/32,nw_proto :ICMP,actions:ALLOW,priority:10}'
url ='http:// localhost:8080 / firewall / rules / 0000000000000001'
req =
f = urllib2.urlopen(req)
for x in f:
print(x)$ urlib2.Request(url,data,{'Content-Type':'application / json'
f.close()


I am trying to execute a curl command within a python script.

If I do it in the terminal, it looks like this:

curl -X POST -d  '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001

I've seen recommendations to use pycurl, but I couldn't figure out how to apply it to mine.

I tried using:

subprocess.call([
    'curl',
    '-X',
    'POST',
    '-d',
    flow_x,
    'http://localhost:8080/firewall/rules/0000000000000001'
])

and it works, but is there a better way?

解决方案

You could use urllib as @roippi said:

import urllib2
data = '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
url = 'http://localhost:8080/firewall/rules/0000000000000001'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
for x in f:
    print(x)
f.close()

这篇关于在Python脚本中执行curl命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆