Best Python code snippet using localstack_python
ec2.py
Source:ec2.py  
...547        else:548            print(e)549    except KeyboardInterrupt:550        print("CTRL-C received, exiting...")551def get_console_screenshot(instanceid, region):552    '''553    Get console screenshot of the specified InstanceID in the specified region554    '''555    try:556        client = boto3.client('ec2', region_name=region)557        print("[INFO] Checking for required permissions to screenshot: {} on {} [INFO]" .format(instanceid, region))558        response = client.get_console_screenshot(DryRun=True, InstanceId=instanceid, WakeUp=True)559        # print(response)560    except botocore.exceptions.ClientError as e:561        if e.response['Error']['Code'] == 'DryRunOperation':562            print('[+] {} : Has permissions...proceeding with the screenshot attempt [+]' .format(AWS_ACCESS_KEY_ID))563            response = client.get_console_screenshot(DryRun=False, InstanceId=instanceid, WakeUp=True)564            print('[+] Writing screenshot to screenshots/{}.png [+]'.format(instanceid))565            file = open('{}/screenshots/{}.png'.format(os.getcwd(), instanceid), "wb")566            file.write(base64.b64decode(response['ImageData']))567            file.close568            # print(response)569        elif e.response['Error']['Code'] == 'UnauthorizedOperation':570            print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))571        elif e.response['Error']['Code'] == 'SubscriptionRequiredException':572            print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))573        else:574            print(e)575    except KeyboardInterrupt:576        print("CTRL-C received, exiting...")577def get_console_screenshot_all():578    '''579    loop through all regions and attempt to screenshot580    '''581    try:582        for region in regions:583            try:584                client = boto3.client('ec2', region_name=region)585                response = client.describe_instances()586            except botocore.exceptions.ClientError as e:587                if e.response['Error']['Code'] == 'UnauthorizedOperation':588                    print('{} : (UnauthorizedOperation) when calling describe_instances -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))589                    sys.exit()590                else:591                    print(e)592            if len(response['Reservations']) <= 0:593                print("[-] List instances allowed for {} but no results [-]" .format(region))594            else:595                # print (response)596                print("[+] Listing instances for region: {} [+]" .format(region))597                for r in response['Reservations']:598                    for i in r['Instances']:599                        instanceid = i['InstanceId']600                        if i['State']['Name'] == "running":601                            try:602                                client = boto3.client('ec2', region_name=region)603                                print("[INFO] Checking for required permissions to screenshot: {} on {} [INFO]" .format(instanceid, region))604                                response = client.get_console_screenshot(DryRun=True, InstanceId=instanceid, WakeUp=True)605                            except botocore.exceptions.ClientError as e:606                                if e.response['Error']['Code'] == 'DryRunOperation':607                                    print('[+] {} : Has permissions...proceeding with the screenshot attempt [+]' .format(AWS_ACCESS_KEY_ID))608                                    response = client.get_console_screenshot(DryRun=False, InstanceId=instanceid, WakeUp=True)609                                    print('[+] Writing screenshot to screenshots/{}.png [+]'.format(instanceid))610                                    file = open('{}/screenshots/{}.png'.format(os.getcwd(), instanceid), "wb")611                                    file.write(base64.b64decode(response['ImageData']))612                                    file.close613                                    # print(response)614                                elif e.response['Error']['Code'] == 'UnauthorizedOperation':615                                    print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))616                                elif e.response['Error']['Message'] == 'InternalError':617                                    print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))618                                elif e.response['Error']['Code'] == 'InternalError':619                                    print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))620                                elif e.response['Error']['Code'] == 'SubscriptionRequiredException':621                                    print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))622                                else:623                                    print(e)624    except botocore.exceptions.ClientError as e:625        if e.response['Error']['Code'] == 'UnauthorizedOperation':626            print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))627        elif e.response['Error']['Code'] == 'SubscriptionRequiredException':628            print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))629        else:630            print(e)631    except KeyboardInterrupt:632        print("CTRL-C received, exiting...")633def get_console_screenshot_all_region(region):634    '''635    Attempt to get screenshots of all EC2 instances in a specified region636    '''637    try:638            client = boto3.client('ec2', region_name=region)639            response = client.describe_instances()640            if len(response['Reservations']) <= 0:641                print("[-] List instances allowed for {} but no results [-]" .format(region))642            else:643                # print (response)644                print("[+] Listing instances for region: {} [+]" .format(region))645                for r in response['Reservations']:646                    for i in r['Instances']:647                        instanceid = i['InstanceId']648                        if i['State']['Name'] == "running":649                            try:650                                client = boto3.client('ec2', region_name=region)651                                print("[INFO] Checking for required permissions to screenshot: {} on {} [INFO]" .format(instanceid, region))652                                response = client.get_console_screenshot(DryRun=True, InstanceId=instanceid, WakeUp=True)653                            except botocore.exceptions.ClientError as e:654                                if e.response['Error']['Code'] == 'DryRunOperation':655                                    print('[+] {} : Has permissions...proceeding with the screenshot attempt [+]' .format(AWS_ACCESS_KEY_ID))656                                    response = client.get_console_screenshot(DryRun=False, InstanceId=instanceid, WakeUp=True)657                                    print('[+] Writing screenshot to screenshots/{}.png [+]'.format(instanceid))658                                    file = open('{}/screenshots/{}.png'.format(os.getcwd(), instanceid), "wb")659                                    file.write(base64.b64decode(response['ImageData']))660                                    file.close661                                    # print(response)662                                elif e.response['Error']['Code'] == 'UnauthorizedOperation':663                                    print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))664                                elif e.response['Error']['Message'] == 'InternalError':665                                    print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))666                                elif e.response['Error']['Code'] == 'InternalError':667                                    print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))668                                elif e.response['Error']['Code'] == 'SubscriptionRequiredException':669                                    print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))670                                elif e.response['Error']['Code'] == 'InvalidInstanceID.NotFound':671                                    print('{} : instance not found' .format(AWS_ACCESS_KEY_ID))672                                else:673                                    print(e)674    except botocore.exceptions.ClientError as e:675        if e.response['Error']['Code'] == 'UnauthorizedOperation':676            print('{} : (UnauthorizedOperation) when calling the DescribeVolumes -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))677        elif e.response['Error']['Code'] == 'SubscriptionRequiredException':678            print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))679        else:680            print(e)681    except KeyboardInterrupt:682        print("CTRL-C received, exiting...")683def get_console_screenshot_all_region_list(file, region):684    '''685    Read a list of ec2 instanceIDs and attempt to screenshot them. They need to be in the same region686    see write_instances_to_file to get a list of instances by region687    '''688    try:689        client = boto3.client('ec2', region_name=region)690        alist = [line.rstrip() for line in open(file)]691        for line in alist:692            try:693                print("[INFO] Checking for required permissions to screenshot: {} on {} [INFO]" .format(line, region))694                response = client.get_console_screenshot(DryRun=True, InstanceId=line, WakeUp=True)695            except botocore.exceptions.ClientError as e:696                if e.response['Error']['Code'] == 'DryRunOperation':697                    print('[+] {} : Has permissions...proceeding with the screenshot attempt [+]' .format(AWS_ACCESS_KEY_ID))698                    response = client.get_console_screenshot(DryRun=False, InstanceId=line, WakeUp=True)699                    print('[+] Writing screenshot to screenshots/{}.png [+]'.format(line))700                    file = open('{}/screenshots/{}.png'.format(os.getcwd(), line), "wb")701                    file.write(base64.b64decode(response['ImageData']))702                    file.close703                    # print(response)704                elif e.response['Error']['Code'] == 'UnauthorizedOperation':705                    print('{} : (UnauthorizedOperation) when calling get_console_screenshot -- sure you have required ec2 permissions?' .format(AWS_ACCESS_KEY_ID))706                elif e.response['Error']['Message'] == 'InternalError':707                    print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))708                elif e.response['Error']['Code'] == 'InternalError':709                    print('{} : Has permissions but an internal error occured - check manually' .format(AWS_ACCESS_KEY_ID))710                elif e.response['Error']['Code'] == 'SubscriptionRequiredException':711                    print('{} : Has permissions but isnt signed up for service - usually means you have a root account' .format(AWS_ACCESS_KEY_ID))712                else:...RekognizeMyEC2Screenshot.py
Source:RekognizeMyEC2Screenshot.py  
...15   16    for bucket in buckets['Buckets']:17        bucket1 = bucket['Name']18        19    console_screenshot = ec2.get_console_screenshot(20        InstanceId=instance_id21        )22        23    fileName = 'ConsoleScreenShot-400' + '.png'24    bbucket = bucket125    base32 = console_screenshot["ImageData"]26    27    28    s3.put_object(Bucket=bbucket, Key=fileName, Body=base32)29    30    return ('Image Successful uploaded to S3 Bucket: ' + bucket1)31    
...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
