小编kma*_*ada的帖子

如何在 python 中设置代理值并运行 linux 命令

在 Linux 中,要设置代理值,请执行以下操作。

proxy=http://$user:$password@proxy.server.com:${NUM}
http_proxy="$proxy" https_proxy="$proxy" ${COMMAND}
Run Code Online (Sandbox Code Playgroud)

出于安全原因,如果您在子 shell 中运行此命令,则不会明确将您的密码公开或记录在日志中。这种方法的问题是,每次我想运行命令时都必须设置用户名和密码。

因此决定为其编写一段python代码。我有一个 C 语言的工作版本。只是想了解更多 Python 知识。我找到了编码和解码密码的好方法,在经历了大部分的麻烦之后,我将其传递给这个函数来测试代理连接。

def test_connection(creds,proxy_url):
    import pycurl
    import cStringIO

    buf = cStringIO.StringIO()
    test_url="http://www.google.com"

    c = pycurl.Curl()
    c.setopt(c.URL, test_url)
    c.setopt(c.WRITEFUNCTION, buf.write)
    c.setopt(c.PROXY, proxy_url)
    c.setopt(c.PROXYPORT, 8080)
    c.setopt(c.PROXYTYPE, c.PROXYTYPE_HTTP) 
    c.setopt(c.PROXYAUTH, c.HTTPAUTH_NTLM) 
    c.setopt(c.PROXYUSERPWD, creds) 
    c.perform()
    buf.close()
    return c.getinfo(c.RESPONSE_CODE)
Run Code Online (Sandbox Code Playgroud)

我遇到问题的地方是使用 suprocess,我确实知道 subprocess 不允许您使用导出,因为它并不是真正的命令。Linux 上的 python 中的“导出”子进程模块错误?

这是我的实现

finalCommand = ["/bin/sh", "-c"]
finalCommand.append(http_proxy)
finalCommand.append(https_proxy)
for x in bashCommand:
    finalCommand.append(x)

print subprocess.call(finalCommand)
process = subprocess.Popen(finalCommand,stdout=subprocess.PIPE)


out, err = process.communicate()

print "Output ... \n %s" …
Run Code Online (Sandbox Code Playgroud)

python linux shell proxy curl

1
推荐指数
1
解决办法
6169
查看次数

标签 统计

curl ×1

linux ×1

proxy ×1

python ×1

shell ×1