【问题标题】:Simple Python script calculates checksum from a web page简单的 Python 脚本从网页计算校验和
【发布时间】:2014-01-21 03:13:53
【问题描述】:

我需要一个简单的 web 服务,我可以在其中传递 URL 作为参数并取回其内容的校验和作为结果。

所以我正在寻找一个简单的 Python 脚本,它从 Internet 获取 URL 并输出 SHA-2 校验和。

有人做过这样的事吗?

【问题讨论】:

    标签: python web-services apache cgi


    【解决方案1】:

    hashlib 似乎没有 sha2,但这里是 sha256:

    #!/usr/local/cpython-3.3/bin/python
    
    import sys
    import hashlib
    import urllib.request
    
    def main():
        url = sys.argv[1]
        response = urllib.request.urlopen(url)
        hasher = hashlib.sha256()
        for block in response.read(2**18):
            text = response.read()
            hasher.update(text)
        print(hasher.hexdigest())
    
    main()
    

    【讨论】:

    • 我真的很喜欢针对简单问题的简单直接的解决方案。恭喜。
    • Hashlib 的 SHA256 是 SHA-2 256
    • @dstromberg 为什么当我计算从提供的 URL 下载的文件的 sha256sum 时,我得到了不同的校验和。它们应该是相同的。为什么?
    • 可能是不同的摘要算法。
    猜你喜欢
    • 2012-10-16
    • 2010-12-18
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2011-04-28
    • 1970-01-01
    相关资源
    最近更新 更多