使用Python检查本地帐户是否有空密码

时间:2017-02-27 15:01:22

标签: python windows powershell

我正在尝试构建一个脚本,用于检查当前登录用户的本地帐户中的密码是否具有Windows中非空白的密码。我需要将其作为安全合规性的后台检查的一部分运行;它将向Nagios服务器报告。我需要在Python中完成这项工作,但如果Python不这样做,我会对PowerShell开放。

因此,脚本需要检测:

  • 当前登录用户的用户名。
  • 上述用户是否有密码空白。
  • 如果密码为空,则返回错误代码0,如果是,则返回错误代码。

我坚持认为只要有一点代码可以检查当前用户的密码是否为“”。我有一个布局,没有太多的装饰,看起来像这样:

import os
import Tkinter
import tkMessageBox
from Tkinter import Tk, Toplevel

MyGui.update_idletasks()
MyGui.attributes('-topmost', True)
MyGui.geometry('{}x{}'.format(300, 150))
MyGui.resizable(width=False, height=False)
MyGui.withdraw()

ThisUser = os.getlogin()
ThisPassword = ...  # line of code necessary to test for blank password; this is the part where I'm stuck

if ThisPassword = "":
    tkMessageBox.showerror("Error For User Here", parent=MyGui)
    print "No password set!"
    sys.exit(2)
else:
    print "Password exists."
    sys.exit(0)

我发现了this article,其中使用了WinAPI推荐LogonUser,但我对C#并不熟悉。 Python更适合我的舒适区域,我无法弄清楚如何检查密码集是否为空。我不想收集密码本身。

1 个答案:

答案 0 :(得分:0)

如果用户的密码不为空,则尝试使用空白密码登录将失败,并显示错误代码ERROR_LOGON_FAILURE。如果它为空,则登录将成功,或者,如果系统策略禁止空密码,则将失败并显示错误代码ERROR_ACCOUNT_RESTRICTION。例如:

import winerror
import win32security

def is_password_blank(username):
    try:
        token = win32security.LogonUser(username, None, '',
                    win32security.LOGON32_LOGON_INTERACTIVE,
                    win32security.LOGON32_PROVIDER_DEFAULT)
    except win32security.error as e:
        if e.winerror == winerror.ERROR_ACCOUNT_RESTRICTION:
            return True
        elif e.winerror == winerror.ERROR_LOGON_FAILURE:
            return False
        raise
    else:
        token.Close()
        return True