ViperSniper0501
ViperSniper0501

Reputation: 310

How to add a user to Windows 10 using python and powershell

I am trying to add a user to windows 10 using a python script that uses powershell to add the user.

Here is what I have so far:

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 + "}"])

Also if it helps, this is the Powershell code that I am basing it off of which does work:

$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

When I execute this python code, I do not get any errors, but I also do not get an added user named testUser. What am I doing wrong?

Any help is greatly appreciated

Upvotes: 1

Views: 3827

Answers (2)

turtlesXD
turtlesXD

Reputation: 57

If anyone wants a different method since this has already been answered but I had errors using it, you can try this. It runs a different command that adds a user with a username and password, however, you need to run the script with pyauc for elevated permission:

import subprocess
import pyuac

user='ABC122'
password='ABC122'

if __name__ == "__main__":
    if not pyuac.isUserAdmin():
        print("Re-launching as admin!")
        pyuac.runAsAdmin()
    else:    
     subprocess.run(['net','user',user,password,'/add'])
     input()

You don't need the input at the end. I just used it so the command window doesn't automatically close, so you can see the output.

Upvotes: 1

ViperSniper0501
ViperSniper0501

Reputation: 310

Found out that I had just a bunch of syntax errors. I feel really dumb now. Here is the correct code on how to add a user to windows 10 through python.

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 + "}"])

Upvotes: 2

Related Questions