Python 从代理捕获环境变量

0 投票
1 回答
597 浏览
提问于 2025-04-17 12:11

当我用一个外部的bash脚本处理我的代理时,我得到了所有的环境变量。

#!/bin/bash

CAPTURE_FILE=/var/log/capture_data
env >> ${CAPTURE_FILE}

# we use exit code 1 to ensure this does not effect the actual browsing
exit 1
#

这个脚本在客户端访问网页时的输出:

HTTP_PORT=80
HTTP_HOST=ads.cnn.com
SERVER[adserver]=ad3ad3:9678:1
CLIENT[referer]=http://edition.cnn.com/
HTTP_PROTO=http
CLIENT[host]=ads.cnn.com
SERVER[vary]=Cookie
SERVER[connection]=Keep-Alive
CLIENTID=2
USERNAME=anonymous@192.168.221.1
SERVER[keep-alive]=timeout=5, max=15
SERVER[date]=Thu, 02 Feb 2012 12:09:46 GMT
SERVER[content-type]=text/html
CLIENT[user-agent]=Safari
PWD=/
VERSION=SR.4.2.2.MR.20110523

现在,我使用了os.environ在python中(感谢之前这里的一位帖子),它可以工作,但只在终端中有效,而当代理把所有请求传递给它时就不行了。

#!/usr/bin/env python

import os
import sys

def capture():

    log = os.environ
    data = open("/tmp/capture.log", "a")
    for key in log.keys():
        data.write((key))
        data.write(" : ")
        for n in log[key]:
            data.write('%s' % ((n)))
        data.write("\n")
    data.close()
    sys.exit(1)

def main():

    capture()

if __name__ == "__main__":
    main()

我可以从标准输入中读取数据,使用sys.stdin.readlines(),但当代理把请求重定向到脚本时,我从环境变量中得到的结果更准确……

有没有人知道为什么这个python脚本不显示任何数据?

来自/var/log/messages的日志:

Feb  3 22:29:02 safesquid capture.py: abrt: detected unhandled Python exception in /opt/safesquid/safesquid/scripts/capture.py
Feb  3 22:30:00 safesquid capture.py: abrt: detected unhandled Python exception in /opt/safesquid/safesquid/scripts/capture.py
Feb  3 22:30:00 safesquid capture.py: abrt: detected unhandled Python exception in /opt/safesquid/safesquid/scripts/capture.py
Feb  3 22:30:01 safesquid capture.py: abrt: detected unhandled Python exception in /opt/safesquid/safesquid/scripts/capture.py

已解决:

我把这个脚本移植到centos 6.2上,它就能正常工作了……看来在fedora上有问题。

1 个回答

1

如果你想要和unix的 env 命令一样的输出,那你可以直接调用这个命令吗?

log = subprocess.check_output("env")

撰写回答