【问题标题】:How to add a user to Windows 10 using python and powershell如何使用 python 和 powershell 将用户添加到 Windows 10
【发布时间】:2020-07-25 00:41:16
【问题描述】:

我正在尝试使用 python 脚本将用户添加到 Windows 10,该脚本使用 powershell 添加用户。

这是我目前所拥有的:

main.py

import subprocess as sub
import os


username = testUser
passwds = passwordTest

command = """
$nusnm = """ + '"{}"'.format(username) + """
$nuspss = ConvertTo-SecureString """ + '"{}"'.format(passwds) + """ -AsPlainText -Force
New-LocalUser -Name $nusnm -Password $nuspss
Add-LocalGroupMember -Group "Administrators" -Member $nusnm
Get-LocalUser
"""
print(command)
exec = sub.Popen(["powershell","& {" + command + "}"])

另外,如果它有帮助,这是我所基于的 Powershell 代码,它确实有效:

$nusnm = Read-Host -Prompt 'What would you like the name of the user to be? '
$nuspss = Read-Host -Prompt -AsSecureString 'Please input a new password for the user '
New-LocalUser $nusnm -Password $nuspss -Confirm
Add-LocalGroupMember -Group "Administrators" -Member $nusnm
Get-LocalUser

当我执行这个 python 代码时,我没有得到任何错误,但我也没有得到一个名为 testUser 的添加用户。我究竟做错了什么?

非常感谢任何帮助

【问题讨论】:

  • 你试过自己执行powershell代码吗?

标签: python-3.x windows powershell subprocess


【解决方案1】:

发现我只有一堆语法错误。我现在真的觉得很傻。这是关于如何通过python将用户添加到Windows 10的正确代码。

main.py

import subprocess as sub
import os


username = testUser
passwds = passwordTest

command = """
$nusnm = """ + '"{}"'.format(username) + """
$nuspss = ConvertTo-SecureString """ + '"{}"'.format(passwds) + """ -AsPlainText -Force
New-LocalUser -Name $nusnm -Password $nuspss
Add-LocalGroupMember -Group "Administrators" -Member $nusnm
Get-LocalUser
"""
print(command)
exec = sub.Popen(["powershell","& {" + command + "}"])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 2013-12-20
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 2015-02-16
    相关资源
    最近更新 更多