urllib2.urlopen 手工調用沒問題,通過crontab調用報錯 [Errno 110] Connection timed out

背景:

準備實現一個腳本,用來監控進程是否還存在,如果不存在,通過調用企業微信機器人回調地址來通知羣內的人員

問題現場:

手工調用,python notify.py   可以正確通知。但是將腳本加入crontab,每分鐘執行一次時,腳本有執行,但是無法通知羣內用戶。

通過日誌定位,報錯信息爲“<urlopen error [Errno 110] Connection timed out>”

問題解決方法:

通過定位,懷疑是crontab方式網絡代理沒有生效,通過顯示設置代理解決:

如果手動可以成功,crontab方式不行,說明機器上是存在代理的。可以通過env|grep proxy來找到

方式1:

通過import os,設置代理

    try:
        os.environ['https_proxy'] = 'https://xxx.com:8080'
        os.environ['http_proxy'] = 'http://xxx.com:8080'


        req = urllib2.Request(uri)
        req.add_header('Content-Type', 'application/json')
        r = urllib2.urlopen(req, json.dumps(data))
        return r
    except Exception as e:
        print e

方式2:

通過urllib2


        proxy_info = { 'host' : 'xxx.com',
               'port' : 8080
             }

        # We create a handler for the proxy
        proxy_support = urllib2.ProxyHandler({"https" : "https://%(host)s:%(port)d" % proxy_info})

        # We create an opener which uses this handler:
        opener = urllib2.build_opener(proxy_support)

        # Then we install this opener as the default opener for urllib2:
        urllib2.install_opener(opener)
        '''

        req = urllib2.Request(uri)
        req.add_header('Content-Type', 'application/json')
        r = urllib2.urlopen(req, json.dumps(data))
        return r
    except Exception as e:
        print e

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章