【发布时间】:2020-04-07 20:09:47
【问题描述】:
我有多个网络接口,并希望使用特定接口发送数据。
这是我使用pycurl的代码:
def curl_post(url, data, iface=None):
c = pycurl.Curl()
buffer = BytesIO()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.POST, True)
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json'])
c.setopt(pycurl.TIMEOUT, 10)
c.setopt(pycurl.WRITEFUNCTION, buffer.write)
c.setopt(pycurl.POSTFIELDS, data)
if iface:
c.setopt(pycurl.INTERFACE, iface)
c.perform()
# Json response
resp = buffer.getvalue().decode('UTF-8')
try:
resp = json.loads(resp)
except json.decoder.JSONDecodeError:
pass
buffer.close()
c.close()
return resp
dat = {"id": 52, "configuration": [{"eno1": {"address": "192.168.1.1"}}]}
res = curl_post("https://emapp.cc/get_my_ip", json.dumps(dat), "enp0s20u1u3")
print(res)
代码在使用sudo 运行时有效,但如果我以标准用户身份运行它会超时。
使用bash 而不使用sudo 会以同样的方式失败:
curl --interface enp0s20u1u3 google.com
我的默认接口是enp4s0f2,当我将其设置为我的代码时,无需使用sudo。
【问题讨论】:
-
更正了格式和语法。
标签: python linux bash curl pycurl