Last active
August 7, 2019 03:32
-
-
Save ejdoh1/332d64916f2d4c998a6db7096547386b to your computer and use it in GitHub Desktop.
AWS SSM Powershell Run Command To Delete User and Profile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import time | |
INSTANCE_ID = "REPLACE_ME" | |
USERNAME = "REPLACE_ME" | |
SSM_RC_DOC_NAME = "AWS-RunPowerShellScript" | |
CMD_STATUS_SUCCESS = "Success" | |
CMD_WAIT_TIME = 2 | |
CMD = f""" | |
# Delete the user profile | |
$profile = Get-WmiObject Win32_UserProfile -ComputerName "localhost" | where {{$_.localpath -eq 'C:\\Users\\{USERNAME}'}} | |
$profile.Delete() | |
# Delete the user account | |
$Computer = [ADSI]"WinNT://$Env:COMPUTERNAME" | |
$Computer.Delete("User", '{USERNAME}') | |
""" | |
c = boto3.client('ssm') | |
r = c.send_command( | |
InstanceIds=[ | |
INSTANCE_ID | |
], | |
DocumentName=SSM_RC_DOC_NAME, | |
Parameters={ | |
'commands': [ | |
CMD | |
] | |
} | |
) | |
print(f"Received command ID {r['Command']['CommandId']}") | |
while True: | |
time.sleep(CMD_WAIT_TIME) | |
r = c.get_command_invocation( | |
CommandId=r['Command']['CommandId'], | |
InstanceId=INSTANCE_ID, | |
) | |
print(f"Command status is: {r['Status']}") | |
if r['Status'] == CMD_STATUS_SUCCESS: | |
break | |
print("---OUTPUT CONTENT---") | |
print(r['StandardOutputContent']) | |
print("---ERROR CONTENT---") | |
print(r['StandardErrorContent']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment