Last active
August 7, 2019 02:08
-
-
Save ejdoh1/e32b758c28c68a027142ab9e1d3d584e to your computer and use it in GitHub Desktop.
Boto3 AWS-RunPowerShellScript Example
This file contains 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_WITH_EC2_INSTANCE_ID" | |
SSM_RC_DOC_NAME = "AWS-RunPowerShellScript" | |
CMD_STATUS_SUCCESS = "Success" | |
CMD_WAIT_TIME = 2 | |
CMD = "ipconfig" | |
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']) |
This file contains 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_WITH_EC2_INSTANCE_ID" | |
USERNAME = "REPLACE_WITH_USERNAME" | |
SSM_RC_DOC_NAME = "AWS-RunPowerShellScript" | |
CMD_STATUS_SUCCESS = "Success" | |
CMD_WAIT_TIME = 2 | |
CMD = f""" | |
$username = "{USERNAME}" | |
$sessionId = ((quser /server:localhost | Where-Object {{ $_ -match $username }}) -split ' +')[2] | |
logoff $sessionId /server:localhost | |
""" | |
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