[英]"curl and pycurl" not working without sudo
我有多個網絡接口,並希望使用特定接口發送數據。
這是我使用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
運行時有效,但如果我以標准用戶身份運行它會超時。
在沒有sudo
情況下使用bash
以同樣的方式失敗:
curl --interface enp0s20u1u3 google.com
我的默認界面是enp4s0f2
,當我將其設置為我的代碼時,無需使用sudo
。
從 curl 手冊頁:
curl --interface eth0:1 https://www.example.com/
If this option is used several times, the last one will be used.
On Linux it can be used to specify a VRF, but the binary needs to either have CAP_NET_RAW or to be ran as root. More information about Linux VRF:
https://www.kernel.org/doc/Documentation/networking/vrf.txt
換句話說,要使 curl 在所有接口上運行而無需 sudo 運行以下命令一次:
sudo setcap CAP_NET_RAW+ep /usr/bin/curl
要恢復此設置,請運行:
sudo setcap CAP_NET_RAW-ep /usr/bin/curl
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.