使用Python的集成Windows身份验证(NTLM)通过Exchange进行SMTP

使用Python的集成Windows身份验证(NTLM)通过Exchange进行SMTP,第1张

使用Python的集成Windows身份验证(NTLM)通过Exchange进行SMTP

尽管下面的解决方案仅使用Python Win32扩展(Python Win32扩展附带的sspi示例代码非常有帮助),但问题中提到的python-ntlm
IMAP和SMTP修补程序也可作为有用的指南。

from smtplib import SMTPException, SMTPAuthenticationErrorimport stringimport base64import sspi# NTLM Guide -- http://curl.haxx.se/rfc/ntlm.htmlSMTP_EHLO_OKAY = 250SMTP_AUTH_CHALLENGE = 334SMTP_AUTH_OKAY = 235def asbase64(msg):    # encoding the message then convert to string    return base64.b64enpre(msg).depre("utf-8")def connect_to_exchange_as_current_user(smtp):    """Example:    >>> import smtplib    >>> smtp = smtplib.SMTP("my.smtp.server")    >>> connect_to_exchange_as_current_user(smtp)    """    # Send the SMTP EHLO command    pre, response = smtp.ehlo()    if pre != SMTP_EHLO_OKAY:        raise SMTPException("Server did not respond as expected to EHLO command")    sspiclient = sspi.ClientAuth('NTLM')    # Generate the NTLM Type 1 message    sec_buffer=None    err, sec_buffer = sspiclient.authorize(sec_buffer)    ntlm_message = asbase64(sec_buffer[0].Buffer)    # Send the NTLM Type 1 message -- Authentication Request    pre, response = smtp.docmd("AUTH", "NTLM " + ntlm_message)    # Verify the NTLM Type 2 response -- Challenge Message    if pre != SMTP_AUTH_CHALLENGE:        raise SMTPException("Server did not respond as expected to NTLM negotiate message")    # Generate the NTLM Type 3 message    err, sec_buffer = sspiclient.authorize(base64.deprebytes(response))    ntlm_message = asbase64(sec_buffer[0].Buffer)    # Send the NTLM Type 3 message -- Response Message    pre, response = smtp.docmd(ntlm_message)    if pre != SMTP_AUTH_OKAY:        raise SMTPAuthenticationError(pre, response)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5508355.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存