【问题标题】:Python sockets suddenly timing out?Python 套接字突然超时?
【发布时间】:2010-09-10 16:39:30
【问题描述】:

我今天回到了通过 SSL 登录 Gmail 的旧脚本。该脚本在我上次运行它时运行良好(几个月前),但现在它立即死亡:

<urlopen error The read operation timed out>

如果我设置了超时时间(不管多长时间),它会更立即死亡:

<urlopen error The connect operation timed out>

后者可通过以下方式重现:

import socket
socket.setdefaulttimeout(30000)
sock = socket.socket()
sock.connect(('www.google.com', 443))
ssl = socket.ssl(sock)

返回:

socket.sslerror: The connect operation timed out

但我似乎无法重现前者,并且在多次浏览代码之后,我不知道是什么原因造成的。

【问题讨论】:

  • Python 是什么版本的?
  • 请指定更多信息。我无法重现您的问题。
  • 平台也会有所帮助。

标签: python api sockets ssl gmail


【解决方案1】:
import socket
socket.setdefaulttimeout(30000)
sock = socket.socket()
sock.connect(('www.google.com', 443))
ssl = socket.ssl(sock)
ssl.server()
--> '/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com'

它工作得很好。我无法重现您的错误。

【讨论】:

    【解决方案2】:

    无法通过 HTTPS 访问 www.google.com。它重定向到不安全的 HTTP。要获取邮件,您应该去https://mail.google.com

    【讨论】:

      【解决方案3】:

      我要检查的第一件事是您是否需要通过 HTTP 代理进行连接(在这种情况下,绕过代理的直接连接可能会超时)。运行 Wireshark 看看会发生什么。

      【讨论】:

        【解决方案4】:

        连接到www.google.com 没有超时,但 Python 3.x 现在提供了ssl 模块,因此 OP 的示例代码将不起作用。

        以下是适用于当前 Python 版本的类似内容:

        import ssl
        import socket
        from pprint import pprint
        
        
        hostname = 'www.google.org'
        context = ssl.create_default_context()
        
        with socket.create_connection((hostname, 443)) as sock:
            with context.wrap_socket(sock, server_hostname=hostname) as ssock:
                pprint(ssock.getpeercert()['subject'])
        

        产生:

        ((('countryName', 'US'),),
         (('stateOrProvinceName', 'California'),),
         (('localityName', 'Mountain View'),),
         (('organizationName', 'Google LLC'),),
         (('commonName', 'misc.google.com'),))
        

        在此处阅读有关 ssl 模块的更多信息:https://docs.python.org/3/library/ssl.html

        【讨论】:

          猜你喜欢
          • 2015-12-07
          • 2016-02-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-27
          • 2016-09-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多