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

2024-09-28 23:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

因此,脚本需要检测:

  • 当前登录用户的用户名。在
  • 无论上述用户的密码是否为空。在
  • 如果密码不为空,则返回错误代码0;如果为空,则返回错误代码2。在

我被困在任何一段代码上,这段代码允许我检查当前用户的密码是否为“”。我有一个布局,没有太多的修饰,看起来像这样:

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更适合我,我只是不知道如何检查密码集是否为空。我不想收集密码本身。在


Tags: 代码用户import脚本false密码ostkinter
1条回答
网友
1楼 · 发布于 2024-09-28 23:22:38

如果用户的密码不为空,则尝试使用空白密码登录将失败,错误代码为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

相关问题 更多 >