• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python ssl.cert_time_to_seconds函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中ssl.cert_time_to_seconds函数的典型用法代码示例。如果您正苦于以下问题:Python cert_time_to_seconds函数的具体用法?Python cert_time_to_seconds怎么用?Python cert_time_to_seconds使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了cert_time_to_seconds函数的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: update

    def update(self):
        """Fetch the certificate information."""
        try:
            ctx = ssl.create_default_context()
            sock = ctx.wrap_socket(
                socket.socket(), server_hostname=self.server_name)
            sock.settimeout(TIMEOUT)
            sock.connect((self.server_name, self.server_port))
        except socket.gaierror:
            _LOGGER.error("Cannot resolve hostname: %s", self.server_name)
            return
        except socket.timeout:
            _LOGGER.error(
                "Connection timeout with server: %s", self.server_name)
            return
        except OSError:
            _LOGGER.error("Cannot connect to %s", self.server_name)
            return

        try:
            cert = sock.getpeercert()
        except OSError:
            _LOGGER.error("Cannot fetch certificate from %s", self.server_name)
            return

        ts_seconds = ssl.cert_time_to_seconds(cert['notAfter'])
        timestamp = datetime.datetime.fromtimestamp(ts_seconds)
        expiry = timestamp - datetime.datetime.today()
        self._state = expiry.days
开发者ID:Khabi,项目名称:home-assistant,代码行数:29,代码来源:cert_expiry.py


示例2: probe

 def probe(self):
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.settimeout(self.timeout)
     ssl_sock = ssl.wrap_socket(s)
     try:
         ssl_sock.connect((self.domain, self.port))
         addr = ssl_sock.getpeername()
         certificate = ssl.get_server_certificate(addr=addr)
     except socket.timeout:
         raise IOError("timeout connecting to %s" % self.domain)
     except:
         # provide a nice error message to caller
         raise IOError("cannot connect to %s" % self.domain)
     finally:
         ssl_sock.close()
     p1 = subprocess.Popen(["openssl", "x509", "-noout", "-enddate"],
                           stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE)
     stdout, _ = p1.communicate(certificate)
     _, expirydate = stdout.split("=")
     expiry_date_in_seconds = ssl.cert_time_to_seconds(expirydate.strip())
     expiry_in_seconds = timedelta_to_seconds(datetime.fromtimestamp(expiry_date_in_seconds) - datetime.now())
     return nagiosplugin.Metric("expiry",
                                value=expiry_in_seconds,
                                uom="s",
                                context="certificate_expiry")
开发者ID:zwopiR,项目名称:monitoring-check_certificate,代码行数:26,代码来源:check_certificate.py


示例3: check_ssl_valid_date

 def check_ssl_valid_date(self, url_data, cert):
     """Check if the certificate is still valid, or if configured check
     if it's at least a number of days valid.
     """
     import ssl
     try:
         notAfter = ssl.cert_time_to_seconds(cert['notAfter'])
     except ValueError as msg:
         msg = _('Invalid SSL certficate "notAfter" value %r') % cert['notAfter']
         url_data.add_warning(msg)
         return
     curTime = time.time()
     # Calculate seconds until certifcate expires. Can be negative if
     # the certificate is already expired.
     secondsValid = notAfter - curTime
     args = dict(expire=cert['notAfter'])
     if secondsValid < 0:
         msg = _('SSL certficate is expired on %(expire)s.')
         url_data.add_warning(msg % args)
     else:
         args['valid'] = strformat.strduration_long(secondsValid)
         if secondsValid < self.warn_ssl_cert_secs_valid:
             msg = _('SSL certificate expires on %(expire)s and is only %(valid)s valid.')
             url_data.add_warning(msg % args)
         else:
             msg = _('SSL certificate expires on %(expire)s and is %(valid)s valid.')
             url_data.add_info(msg % args)
开发者ID:EricR86,项目名称:linkchecker,代码行数:27,代码来源:sslcertcheck.py


示例4: from_ssl_socket

 def from_ssl_socket(cls, ssl_socket):
     """Load certificate data from an SSL socket.
     """
     cert = cls()
     try:
         data = ssl_socket.getpeercert()
     except AttributeError:
         # PyPy doesn't have .getppercert
         return cert
     logger.debug("Certificate data from ssl module: {0!r}".format(data))
     if not data:
         return cert
     cert.validated = True
     cert.subject_name = data.get("subject")
     cert.alt_names = defaultdict(list)
     if "subjectAltName" in data:
         for name, value in data["subjectAltName"]:
             cert.alt_names[name].append(value)
     if "notAfter" in data:
         tstamp = ssl.cert_time_to_seconds(data["notAfter"])
         cert.not_after = datetime.utcfromtimestamp(tstamp)
     if sys.version_info.major < 3:
         cert._decode_names()  # pylint: disable=W0212
     cert.common_names = []
     if cert.subject_name:
         for part in cert.subject_name:
             for name, value in part:
                 if name == "commonName":
                     cert.common_names.append(value)
     return cert
开发者ID:kulikov,项目名称:python-tools,代码行数:30,代码来源:cert.py


示例5: is_ssl_expiring

 def is_ssl_expiring(self, ip_address, port=443, ssl_expiration_days=0):
     # Check site's cert
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     ssl_sock = ssl.wrap_socket(s, ca_certs=get_certs_file(), cert_reqs=ssl.CERT_REQUIRED)
     try:
         ssl_sock.connect((ip_address, port))
         cert = ssl_sock.getpeercert()
         cert_expiration = ssl.cert_time_to_seconds(cert["notAfter"])
         exp = cert_expiration - time.time()
         if exp <= 0: return 1
         elif exp <= (ssl_expiration_days * 24 * 60 * 60): return 2
     except:
         return 3
     finally:
         ssl_sock.shutdown(socket.SHUT_RDWR)
         ssl_sock.close()
     return 0
开发者ID:marqui678,项目名称:finalchance.Panopta,代码行数:17,代码来源:HTTPFullPage.py


示例6: gen_gmtime_dates

def gen_gmtime_dates():
	""" Generate the dates used for this run.
	Creating openssl gmtime dates may be simpler than this.
	"""
	gmtfmt = "%b %d %H:%M:%S %Y GMT"

	ok_stamp = ssl.cert_time_to_seconds(
			time.strftime(gmtfmt, time.gmtime())) - (60*60*24)
	two_days_ago_stamp = ok_stamp - (60*60*48)
	two_days_ago_end_stamp = two_days_ago_stamp + (60*60*24)
	future_stamp = ok_stamp + (60*60*24*365*1)
	future_end_stamp = future_stamp + (60*60*24*365*1)

	return dict(OK_NOW=gmc(ok_stamp),
				OLD=gmc(two_days_ago_stamp),
				OLD_END=gmc(two_days_ago_end_stamp),
			    FUTURE=gmc(future_stamp),
				FUTURE_END=gmc(future_end_stamp))
开发者ID:aveshagarwal,项目名称:libreswan,代码行数:18,代码来源:dist_certs.py


示例7: _validate_certificate

 def _validate_certificate(self, cert):
     now = time.time()
     # Refuse to connect if there's no certificate.
     if cert is None:
         err = "no SSL certificate for %s" % (self.host,)
         raise socket.error(err)
     # Refuse to connect if the certificate has expired.
     if "notAfter" in cert:
         if ssl.cert_time_to_seconds(cert["notAfter"]) < now:
             err = "expired SSL certificate for %s" % (self.host,)
             raise socket.error(err)
     # Refuse to connect if the certificate is missing subject data.
     if "subject" not in cert:
         err = "malformed SSL certificate for %s" % (self.host,)
         raise socket.error(err)
     # Try to match the certificate to the requested host.
     if not self._validate_certificate_hostname(cert):
         err = "invalid SSL certificate for %s" % (self.host,)
         raise socket.error(err)
开发者ID:mozilla-services,项目名称:PyVEP,代码行数:19,代码来源:utils.py


示例8: gen_gmtime_dates

def gen_gmtime_dates():
	""" Generate the dates used for this run.
	Creating openssl gmtime dates may be simpler than this.
	"""
	gmtfmt = "%b %d %H:%M:%S %Y GMT"

	ok_stamp = ssl.cert_time_to_seconds(
			time.strftime(gmtfmt, time.gmtime())) - (60*60*24)
	two_days_ago_stamp = ok_stamp - (60*60*48)
	two_days_ago_end_stamp = two_days_ago_stamp + (60*60*24)
        # Make future certs only +300 days, so we have a time overlap
        # between currently valid certs (1 year) and these futuristic certs
	future_stamp = ok_stamp + (60*60*24*365*1)
	future_end_stamp = future_stamp + (60*60*24*365*2)

	return dict(OK_NOW=gmc(ok_stamp),
				OLD=gmc(two_days_ago_stamp),
				OLD_END=gmc(two_days_ago_end_stamp),
			    FUTURE=gmc(future_stamp),
				FUTURE_END=gmc(future_end_stamp))
开发者ID:doctaweeks,项目名称:libreswan,代码行数:20,代码来源:dist_certs.py


示例9: expiring_certificate

def expiring_certificate(connection, expiry_days):
    '''
    Pass in the connection and number of days. Verify that the expiry date isn't
    within the specified number of days
    '''

    # Convert the presented certificate's expiry date into a datetime object.
    # This could be done in one line, but for readability, we'll do this over three

    expiry_date = connection.getpeercert()['notAfter']
    expiry_epoch = ssl.cert_time_to_seconds(expiry_date)
    expires = datetime.datetime.fromtimestamp(expiry_epoch)

    # Create a datetime object of the specified date
    now = datetime.datetime.now()
    specified_date = now + datetime.timedelta(days=expiry_days)

    # this evalutes to True if the certificate expires before the specified
    # expiry date.

    return expires < specified_date
开发者ID:twirrim,项目名称:checkendpoint,代码行数:21,代码来源:checkendpoint.py


示例10: check_ssl_valid_date

 def check_ssl_valid_date(self, url_data, ssl_sock, cert):
     """Check if the certificate is still valid, or if configured check
     if it's at least a number of days valid.
     """
     import ssl
     try:
         notAfter = ssl.cert_time_to_seconds(cert['notAfter'])
     except ValueError as msg:
         msg = _('invalid certficate "notAfter" value %r') % cert['notAfter']
         self.add_ssl_warning(url_data, ssl_sock, msg)
         return
     curTime = time.time()
     # Calculate seconds until certifcate expires. Can be negative if
     # the certificate is already expired.
     secondsValid = notAfter - curTime
     if secondsValid < 0:
         msg = _('certficate is expired on %s') % cert['notAfter']
         self.add_ssl_warning(url_data, ssl_sock, msg)
     elif secondsValid < self.warn_ssl_cert_secs_valid:
         strSecondsValid = strformat.strduration_long(secondsValid)
         msg = _('certificate is only %s valid') % strSecondsValid
         self.add_ssl_warning(url_data, ssl_sock, msg)
开发者ID:bootstraponline,项目名称:linkchecker,代码行数:22,代码来源:sslcertcheck.py


示例11: __verifycert

    def __verifycert(self, cert, hostname):
        """Verify that cert (in socket.getpeercert() format) matches hostname.

        CRLs are not handled.
        Returns error message if any problems are found and None on success."""

        errstr = "CA Cert verifying failed: "
        if not cert:
            return ('%s no certificate received'% errstr)
        dnsname = hostname.lower()
        certnames = []

        # cert expired?
        notafter = cert.get('notAfter')
        if notafter:
            if time.time() >= cert_time_to_seconds(notafter):
                return '%s certificate expired %s'% (errstr, notafter)

        # First read commonName
        for s in cert.get('subject', []):
            key, value = s[0]
            if key == 'commonName':
                certnames.append(value.lower())
        if len(certnames) == 0:
            return ('%s no commonName found in certificate'% errstr)

        # Then read subjectAltName
        for key, value in cert.get('subjectAltName', []):
            if key == 'DNS':
                certnames.append(value.lower())

        # And finally try to match hostname with one of these names
        for certname in certnames:
            if (certname == dnsname or
                '.' in dnsname and certname == '*.' + dnsname.split('.', 1)[1]):
                return None

        return ('%s no matching domain name found in certificate'% errstr)
开发者ID:OfflineIMAP,项目名称:offlineimap,代码行数:38,代码来源:imapserver.py


示例12: check_validation

def check_validation(host):
	now = time.time()

	context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
	context.verify_mode = ssl.CERT_REQUIRED
	context.check_hostname = True
	context.load_default_certs()

	conn = context.wrap_socket(socket.socket(socket.AF_INET),server_hostname=host)
	conn.connect((host, 443))
	cert = conn.getpeercert()

	ttl = ssl.cert_time_to_seconds(cert['notAfter']) - now
	print(ttl)
	print(ttl/3600/24)

	k = host.split('.')[0]
	if ttl < 0:
		push_metrics("trapper.ssl-certificate.{0}.valid".format(k), 2)
	else:
		push_metrics("trapper.ssl-certificate.{0}.valid".format(k), 1)

	push_metrics("trapper.ssl-certificate.{0}.days".format(k), round(ttl/3600/24, 2))
开发者ID:cf2012,项目名称:workspace,代码行数:23,代码来源:check_https_validation.py


示例13: _cert_expiration_analysis

    def _cert_expiration_analysis(self, url, domain):
        cert, cert_der, cipher = self._get_cert(url, domain)

        try:
            exp_date = gmtime(ssl.cert_time_to_seconds(cert['notAfter']))
        except ValueError:
            msg = 'Invalid SSL certificate date format.'
            om.out.debug(msg)
        except KeyError:
            msg = 'SSL certificate does not have notAfter field.'
            om.out.debug(msg)
        else:
        
            expire_days = (date(exp_date.tm_year, exp_date.tm_mon,
                           exp_date.tm_mday) - date.today()).days
            
            if expire_days < self._min_expire_days:
                desc = 'The certificate for "%s" will expire soon.' % domain
                
                i = Info('Soon to expire SSL certificate', desc, 1, self.get_name())
                i.set_url(url)
                
                self.kb_append(self, 'ssl_soon_expire', i)
开发者ID:Adastra-thw,项目名称:Tortazo,代码行数:23,代码来源:ssl_certificate.py


示例14: _verifycert

    def _verifycert(self, cert, hostname):
        """Verify that cert (in socket.getpeercert() format) matches hostname.
        CRLs are not handled.
        
        Returns error message if any problems are found and None on success.
        """
        if not cert:
            return "no certificate received"
        dnsname = hostname.lower()
        certnames = []

        # cert expired?
        notafter = cert.get("notAfter")
        if notafter:
            if time.time() >= ssl.cert_time_to_seconds(notafter):
                return ("server certificate error: certificate expired %s") % notafter

        # First read commonName
        for s in cert.get("subject", []):
            key, value = s[0]
            if key == "commonName":
                certnames.append(value.lower())
        if len(certnames) == 0:
            return "no commonName found in certificate"

        # Then read subjectAltName
        for key, value in cert.get("subjectAltName", []):
            if key == "DNS":
                certnames.append(value.lower())

        # And finally try to match hostname with one of these names
        for certname in certnames:
            if certname == dnsname or "." in dnsname and certname == "*." + dnsname.split(".", 1)[1]:
                return None

        return "no matching domain name found in certificate"
开发者ID:kmkaplan,项目名称:offlineimap,代码行数:36,代码来源:imaplibutil.py


示例15: gmtime

            v.set_url(url)
            
            self.kb_append(self, tag, v)
            return

        except Exception, e:
            om.out.debug(str(e))
            return

        cert = ssl_sock.getpeercert()
        cert_der = ssl_sock.getpeercert(binary_form=True)
        cipher = ssl_sock.cipher()
        ssl_sock.close()

        exp_date = gmtime(ssl.cert_time_to_seconds(cert['notAfter']))
        expire_days = (date(exp_date.tm_year, exp_date.tm_mon,
                       exp_date.tm_mday) - date.today()).days
        if expire_days < self._min_expire_days:
            desc = 'The certificate for "%s" will expire soon.' % domain
            
            i = Info('Soon to expire SSL certificate', desc, 1, self.get_name())
            i.set_url(url)
            
            self.kb_append(self, 'ssl_soon_expire', i)

        # Print the SSL information to the log
        desc = 'This is the information about the SSL certificate used for'\
               ' %s site:\n%s' % (domain,
                                  self._dump_ssl_info(cert, cert_der, cipher))
        om.out.information(desc)
开发者ID:HamzaKo,项目名称:w3af,代码行数:30,代码来源:ssl_certificate.py


示例16: int

#   limitations under the License.

import argparse
import socket
import ssl
import time

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description=('A script that checks certificate '
                                                'freshness'))
  parser.add_argument('hostname', type=str, help='hostname for a SSL server')
  parser.add_argument('--port', '-p', help='port', default='443')
  parser.add_argument('--original', '-o', help='show original longevity instead',
                      action='store_true')

  args = parser.parse_args()

  ssl_sock = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM),
                             ca_certs='/etc/ssl/certs/ca-certificates.crt',
                             cert_reqs=ssl.CERT_REQUIRED)
  ssl_sock.connect((args.hostname, int(args.port)))

  notAfter = ssl.cert_time_to_seconds(ssl_sock.getpeercert()['notAfter'])
  day = 60 * 60 * 24
  if args.original:
    notBefore = ssl.cert_time_to_seconds(ssl_sock.getpeercert()['notBefore'])
    print (int((notAfter - notBefore) / day))
  else:
    t = time.time()
    print(int((notAfter - t) / day))
开发者ID:dmiyakawa,项目名称:zabbix_external_scripts,代码行数:30,代码来源:get_cert_life.py


示例17: process_task


#.........这里部分代码省略.........


        # Path validation that ran into errors
        for ((store_name, store_version), error_msg) in verify_dict_error.iteritems():
            verify_txt = 'ERROR: ' + error_msg
            text_output.append(self.FIELD_FORMAT(self.TRUST_FORMAT(store_name=store_name,
                                                                   store_version=store_version),
                                                 verify_txt))

        # Print the Common Names within the certificate chain
        cns_in_cert_chain = []
        for cert in x509_cert_chain:
            cert_identity = self._extract_subject_cn_or_oun(cert)
            cns_in_cert_chain.append(cert_identity)

        text_output.append(self.FIELD_FORMAT('Certificate Chain Received:', str(cns_in_cert_chain)))


        # Text output - OCSP stapling
        text_output.extend(['', self.PLUGIN_TITLE_FORMAT('Certificate - OCSP Stapling')])
        text_output.extend(self._get_ocsp_text(ocsp_response))


        # XML output
        xml_output = Element(command, argument=arg, title='Certificate Information')

        # XML output - certificate chain:  always return the full certificate for each cert in the chain
        cert_chain_xml = Element('certificateChain')

        # XML output - expiration date

        # em begin
        cert_dict = x509_cert.as_dict()
        expiration_date = gmtime(cert_time_to_seconds(cert_dict['validity']['notAfter']))
        expire_days = (date(expiration_date.tm_year, expiration_date.tm_mon, expiration_date.tm_mday) - date.today()).days
        expiration_date_xml = Element("expirationDate", notAfter=cert_dict['validity']['notAfter'],
                                      expiresDays=expire_days)
        xml_output.append(expiration_date_xml)
        # em end

        # First add the leaf certificate
        cert_chain_xml.append(self._format_cert_to_xml(x509_cert_chain[0], 'leaf', self._shared_settings['sni']))

        # Then add every other cert in the chain
        for cert in x509_cert_chain[1:]:
            cert_chain_xml.append(self._format_cert_to_xml(cert, 'intermediate', self._shared_settings['sni']))

        xml_output.append(cert_chain_xml)

        # XML output - trust
        trust_validation_xml = Element('certificateValidation')

        # Hostname validation
        is_hostname_valid = 'False' if (x509_cert.matches_hostname(host) == X509_NAME_MISMATCH) else 'True'
        host_validation_xml = Element('hostnameValidation', serverHostname=host,
                                      certificateMatchesServerHostname=is_hostname_valid)
        trust_validation_xml.append(host_validation_xml)

        # Path validation - OK
        for ((store_name, store_version), verify_str) in verify_dict.iteritems():
            path_attrib_xml = {
                'usingTrustStore': store_name,
                'trustStoreVersion': store_version,
                'validationResult': verify_str
            }
开发者ID:ZenSecurity,项目名称:sslyze,代码行数:66,代码来源:PluginCertInfo.py


示例18: gmtime

            v.setPluginName(self.getName())
            v.setURL(url)
            kb.kb.append(self, tag, v)
            om.out.vulnerability(v.getName() + ": " + v.getDesc())
            return

        except Exception, e:
            om.out.debug(str(e))
            return

        cert = ssl_sock.getpeercert()
        cert_der = ssl_sock.getpeercert(binary_form=True)
        cipher = ssl_sock.cipher()
        ssl_sock.close()

        exp_date = gmtime(ssl.cert_time_to_seconds(cert["notAfter"]))
        expire_days = (date(exp_date.tm_year, exp_date.tm_mon, exp_date.tm_mday) - date.today()).days
        if expire_days < self._min_expire_days:
            i = info.info()
            i.setURL(url)
            i.setPluginName(self.getName())
            i.setName("Soon expire SSL certificate")
            i.setDesc('The certificate for "%s" will expire soon.' % domain)
            kb.kb.append(self, "ssl_soon_expire", i)
            om.out.information(i.getDesc())

        # Print the SSL information to the log
        desc = "This is the information about the SSL certificate used in the target site:\n"
        desc += self._dump_ssl_info(cert, cert_der, cipher)
        om.out.information(desc)
        i = info.info()
开发者ID:sanzomaldini,项目名称:w3af,代码行数:31,代码来源:sslCertificate.py



注:本文中的ssl.cert_time_to_seconds函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python ssl.create_default_context函数代码示例发布时间:2022-05-27
下一篇:
Python ssl._create_unverified_context函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap