【问题标题】:"curl and pycurl" not working without sudo“curl 和 pycurl”没有 sudo 就无法工作
【发布时间】: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


【解决方案1】:

来自 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

更多信息见https://security.stackexchange.com/questions/128958/security-implications-of-using-setcap-cap-net-raw

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2015-06-04
    • 2011-01-14
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多