我正在撰寫一段代碼來驗證給定 URL 的 SSL 證書是否有效,但是,請求庫似乎無法正常作業。這是代碼:
import requests
try:
response = str(requests.get(url, verify=True, allow_redirects=True))
print(response)
if "SSL: CERTIFICATE_VERIFY_FAILED" in response:
print("url \"" url "\" has an invalid SSL certificate")
else:
valid = True
for command in commands:
if command.title == "get info":
if command.expirationDate > datetime.date:
print("url has an expired SSL certificate.")
valid = False
if valid:
print("url \"" url "\" has a valid SSL certificate")
except requests.exceptions.InvalidURL:
print("Invalid url \"" url "\"")
except requests.exceptions.MissingSchema:
print("Invalid url \"" url "\"")
except (socket.gaierror, urllib3.exceptions.NewConnectionError, urllib3.exceptions.MaxRetryError, requests.exceptions.ConnectionError):
print("Could not resolve url \"" url "\" to host")
輸入 URL“https://expired.badssl.com/ 回傳
Could not resolve url "https://expired.badssl.com/" to host
但是,我實際上可以導航到此頁面。此外,沒有有效證書的頁面顯示為有效。我的一個朋友在他的牛肉上運行了這個確切的代碼-xss 服務器,輸出是它有一個有效的證書。我看過很多教程都說同樣的話,但是,考慮到我嘗試過的任何東西都不起作用,我一定遺漏了一些東西。
uj5u.com熱心網友回復:
你的問題似乎是你的 IF 陳述句沒有被評估,因為當 SSL 驗證失敗時請求已經拋出例外。
您可能需要使用專用的 try-except 塊來處理它,例如:
import requests
def has_valid_ssl_req(url):
try:
response = str(requests.get(url, verify=True, allow_redirects=True))
print(response)
print(url " has valid SSL, response: " response)
except Exception as e:
print(url ": has INVALID SSL, error:" str(e))
has_valid_ssl_req('http://expired.badssl.com')
has_valid_ssl_req('http://google.com')
基于:如何在 python 中獲取證書頒發者資訊?我可能會直接使用 SSL
import socket
import ssl
def has_valid_ssl(url):
try:
ctx = ssl.create_default_context()
with ctx.wrap_socket(socket.socket(), server_hostname=url) as s:
s.connect((url, 443))
print(url " has valid SSL")
except Exception as e:
print(url ": has INVALID SSL, error:" str(e))
has_valid_ssl('expired.badssl.com')
has_valid_ssl('google.com')
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/328326.html
上一篇:無法建立SSL連接
