Skip to content

Python3

AWS Security Hub work in Python 3 and Boto3

Testing some commands with python3 and boto3

List of AWS Services from Boto3 clients

The below error message, shows very usefull information. I can see all the boto3.client's name that I can use.

Does anyone knows how to get the list without using the error?

Input

import boto3

boto3.client(dir)

output (tweaked to show the services names in a multi line list)

UnknownServiceError: Unknown service: '<built-in function dir>'.

Valid service names are:

accessanalyzer,
account,
acm,
acm-pca,
alexaforbusiness,
amp,
amplify,
amplifybackend,
amplifyuibuilder,
apigateway,
apigatewaymanagementapi,
apigatewayv2,
appconfig,
appconfigdata,
appflow,
appintegrations,
application-autoscaling,
application-insights,
applicationcostprofiler,
appmesh,
apprunner,
appstream,
appsync,
athena,
auditmanager,
autoscaling,
autoscaling-plans,
backup,
backup-gateway,
batch,
braket,
budgets,
ce,
chime,
chime-sdk-identity,
chime-sdk-meetings,
chime-sdk-messaging,
cloud9,
cloudcontrol,
clouddirectory,
cloudformation,
cloudfront,
cloudhsm,
cloudhsmv2,
cloudsearch,
cloudsearchdomain,
cloudtrail,
cloudwatch,
codeartifact,
codebuild,
codecommit,
codedeploy,
codeguru-reviewer,
codeguruprofiler,
codepipeline,
codestar,
codestar-connections,
codestar-notifications,
cognito-identity,
cognito-idp,
cognito-sync,
comprehend,
comprehendmedical,
compute-optimizer,
config,
connect,
connect-contact-lens,
connectparticipant,
cur,
customer-profiles,
databrew,
dataexchange,
datapipeline,
datasync,
dax,
detective,
devicefarm,
devops-guru,
directconnect,
discovery,
dlm,
dms,
docdb,
drs,
ds,
dynamodb,
dynamodbstreams,
ebs,
ec2,
ec2-instance-connect,
ecr,
ecr-public,
ecs,
efs,
eks,
elastic-inference,
elasticache,
elasticbeanstalk,
elastictranscoder,
elb,
elbv2,
emr,
emr-containers,
es,
events,
evidently,
finspace,
finspace-data,
firehose,
fis,
fms,
forecast,
forecastquery,
frauddetector,
fsx,
gamelift,
glacier,
globalaccelerator,
glue,
grafana,
greengrass,
greengrassv2,
groundstation,
guardduty,
health,
healthlake,
honeycode,
iam,
identitystore,
imagebuilder,
importexport,
inspector,
inspector2,
iot,
iot-data,
iot-jobs-data,
iot1click-devices,
iot1click-projects,
iotanalytics,
iotdeviceadvisor,
iotevents,
iotevents-data,
iotfleethub,
iotsecuretunneling,
iotsitewise,
iotthingsgraph,
iottwinmaker,
iotwireless,
ivs,
kafka,
kafkaconnect,
kendra,
kinesis,
kinesis-video-archived-media,
kinesis-video-media,
kinesis-video-signaling,
kinesisanalytics,
kinesisanalyticsv2,
kinesisvideo,
kms,
lakeformation,
lambda,
lex-models,
lex-runtime,
lexv2-models,
lexv2-runtime,
license-manager,
lightsail,
location,
logs,
lookoutequipment,
lookoutmetrics,
lookoutvision,
machinelearning,
macie,
macie2,
managedblockchain,
marketplace-catalog,
marketplace-entitlement,
marketplacecommerceanalytics,
mediaconnect,
mediaconvert,
medialive,
mediapackage,
mediapackage-vod,
mediastore,
mediastore-data,
mediatailor,
memorydb,
meteringmarketplace,
mgh,
mgn,
migration-hub-refactor-spaces,
migrationhub-config,
migrationhubstrategy,
mobile,
mq,
mturk,
mwaa,
neptune,
network-firewall,
networkmanager,
nimble,
opensearch,
opsworks,
opsworkscm,
organizations,
outposts,
panorama,
personalize,
personalize-events,
personalize-runtime,
pi,
pinpoint,
pinpoint-email,
pinpoint-sms-voice,
polly,
pricing,
proton,
qldb,
qldb-session,
quicksight,
ram,
rbin,
rds,
rds-data,
redshift,
redshift-data,
rekognition,
resiliencehub,
resource-groups,
resourcegroupstaggingapi,
robomaker,
route53,
route53-recovery-cluster,
route53-recovery-control-config,
route53-recovery-readiness,
route53domains,
route53resolver,
rum,
s3,
s3control,
s3outposts,
sagemaker,
sagemaker-a2i-runtime,
sagemaker-edge,
sagemaker-featurestore-runtime,
sagemaker-runtime,
savingsplans,
schemas,
sdb,
secretsmanager,
securityhub,
serverlessrepo,
service-quotas,
servicecatalog,
servicecatalog-appregistry,
servicediscovery,
ses,
sesv2,
shield,
signer,
sms,
sms-voice,
snow-device-management,
snowball,
sns,
sqs,
ssm,
ssm-contacts,
ssm-incidents,
sso,
sso-admin,
sso-oidc,
stepfunctions,
storagegateway,
sts,
support,
swf,
synthetics,
textract,
timestream-query,
timestream-write,
transcribe,
transfer,
translate,
voice-id,
waf,
waf-regional,
wafv2,
wellarchitected,
wisdom,
workdocs,
worklink,
workmail,
workmailmessageflow,
workspaces,
workspaces-web,
xray

A curiosity...
I echod all the aww services' names to wc -l to get a count of the services.

See for yourself how many boto3.client client has,
which, should give us an idea of how many services AWS has.

echo "accessanalyzer, account, acm, acm-pca, alexaforbusiness, amp, amplify, amplifybackend, amplifyuibuilder, apigateway, apigatewaymanagementapi, apigatewayv2, appconfig, appconfigdata, appflow, appintegrations, application-autoscaling, application-insights, applicationcostprofiler, appmesh, apprunner, appstream, appsync, athena, auditmanager, autoscaling, autoscaling-plans, backup, backup-gateway, batch, braket, budgets, ce, chime, chime-sdk-identity, chime-sdk-meetings, chime-sdk-messaging, cloud9, cloudcontrol, clouddirectory, cloudformation, cloudfront, cloudhsm, cloudhsmv2, cloudsearch, cloudsearchdomain, cloudtrail, cloudwatch, codeartifact, codebuild, codecommit, codedeploy, codeguru-reviewer, codeguruprofiler, codepipeline, codestar, codestar-connections, codestar-notifications, cognito-identity, cognito-idp, cognito-sync, comprehend, comprehendmedical, compute-optimizer, config, connect, connect-contact-lens, connectparticipant, cur, customer-profiles, databrew, dataexchange, datapipeline, datasync, dax, detective, devicefarm, devops-guru, directconnect, discovery, dlm, dms, docdb, drs, ds, dynamodb, dynamodbstreams, ebs, ec2, ec2-instance-connect, ecr, ecr-public, ecs, efs, eks, elastic-inference, elasticache, elasticbeanstalk, elastictranscoder, elb, elbv2, emr, emr-containers, es, events, evidently, finspace, finspace-data, firehose, fis, fms, forecast, forecastquery, frauddetector, fsx, gamelift, glacier, globalaccelerator, glue, grafana, greengrass, greengrassv2, groundstation, guardduty, health, healthlake, honeycode, iam, identitystore, imagebuilder, importexport, inspector, inspector2, iot, iot-data, iot-jobs-data, iot1click-devices, iot1click-projects, iotanalytics, iotdeviceadvisor, iotevents, iotevents-data, iotfleethub, iotsecuretunneling, iotsitewise, iotthingsgraph, iottwinmaker, iotwireless, ivs, kafka, kafkaconnect, kendra, kinesis, kinesis-video-archived-media, kinesis-video-media, kinesis-video-signaling, kinesisanalytics, kinesisanalyticsv2, kinesisvideo, kms, lakeformation, lambda, lex-models, lex-runtime, lexv2-models, lexv2-runtime, license-manager, lightsail, location, logs, lookoutequipment, lookoutmetrics, lookoutvision, machinelearning, macie, macie2, managedblockchain, marketplace-catalog, marketplace-entitlement, marketplacecommerceanalytics, mediaconnect, mediaconvert, medialive, mediapackage, mediapackage-vod, mediastore, mediastore-data, mediatailor, memorydb, meteringmarketplace, mgh, mgn, migration-hub-refactor-spaces, migrationhub-config, migrationhubstrategy, mobile, mq, mturk, mwaa, neptune, network-firewall, networkmanager, nimble, opensearch, opsworks, opsworkscm, organizations, outposts, panorama, personalize, personalize-events, personalize-runtime, pi, pinpoint, pinpoint-email, pinpoint-sms-voice, polly, pricing, proton, qldb, qldb-session, quicksight, ram, rbin, rds, rds-data, redshift, redshift-data, rekognition, resiliencehub, resource-groups, resourcegroupstaggingapi, robomaker, route53, route53-recovery-cluster, route53-recovery-control-config, route53-recovery-readiness, route53domains, route53resolver, rum, s3, s3control, s3outposts, sagemaker, sagemaker-a2i-runtime, sagemaker-edge, sagemaker-featurestore-runtime, sagemaker-runtime, savingsplans, schemas, sdb, secretsmanager, securityhub, serverlessrepo, service-quotas, servicecatalog, servicecatalog-appregistry, servicediscovery, ses, sesv2, shield, signer, sms, sms-voice, snow-device-management, snowball, sns, sqs, ssm, ssm-contacts, ssm-incidents, sso, sso-admin, sso-oidc, stepfunctions, storagegateway, sts, support, swf, synthetics, textract, timestream-query, timestream-write, transcribe, transfer, translate, voice-id, waf, waf-regional, wafv2, wellarchitected, wisdom, workdocs, worklink, workmail, workmailmessageflow, workspaces, workspaces-web, xray" | tr ' ' '\n' | wc -l
299
(...)  | tr ' ' '\n' | wc -l
299

299 AWS boto3 client or 299 AWS Services? (checked on 2022-03-24)


Working with aws boto3 client securityhub

Here is an example of the second service name. The number [1] shows a second position in the array. [0] if the first position, first value.

input

import boto3

securityhub = boto3.client('securityhub')

securityhub.describe_products()['Products'][1]

output

{'ProductArn': 'arn:aws:securityhub:xxxxxx:xxxxxx:product/armordefense/armoranywhere',
 'ProductName': 'Armor Anywhere',
 'CompanyName': 'ARMOR',
 'Description': 'Armor Anywhere delivers managed security and compliance for AWS.',
 'Categories': ['Managed Security Service Provider (MSSP)'],
 'IntegrationTypes': ['SEND_FINDINGS_TO_SECURITY_HUB'],
 'MarketplaceUrl': 'https://aws.amazon.com/marketplace/seller-profile?id=797425f4-6823-xxxxxx',
 'ActivationUrl': 'https://amp.armor.com/account/cloud-connections',
 'ProductSubscriptionResourcePolicy': '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"xxxxxx"},"Action":["securityhub:BatchImportFindings"],"Resource":"arn:aws:securityhub:xxxxxx:xxxxxx:product-subscription/armordefense/armoranywhere","Condition":{"StringEquals":{"securityhub:TargetAccount":"xxxxxx"}}},{"Effect":"Allow","Principal":{"AWS":"xxxxxx"},"Action":["securityhub:BatchImportFindings"],"Resource":"arn:aws:securityhub:xxxxxx:xxxxxx:product/armordefense/armoranywhere","Condition":{"StringEquals":{"securityhub:TargetAccount":"xxxxxx"}}}]}'}

Now, let's use a for loop to list through all services names.

initialising the variable companies

and running a for loop to add all companies into the variable companies

companies = []

for CompanyName in securityhub.describe_products()['Products']:
    print(CompanyName['CompanyName'])
    companies.append(CompanyName['CompanyName'])

(...)

Then, to remove duplicate services names in the variable companies, we can use dict.fromkeys to remove duplicates.

```python list(dict.fromkeys(companies))

['3CORESec', 'ARMOR', 'AWS', 'Alert Logic', 'Amazon', 'Aqua Security', 'Atlassian', 'AttackIQ', 'Barracuda Networks', 'BigID', 'Blue Hexagon', 'Capitis', 'Caveonix', 'Check Point', 'Cloud Custodian', 'Cloud Storage Security', 'CrowdStrike', 'CyberArk', 'DisruptOps, Inc.', 'FireEye', 'Forcepoint', 'Fugue', 'Guardicore', 'HackerOne', 'IBM'] ```

Python3 start learning first commands

So, if you just start learning Python 3, where are some tips to help you start.

Assume you already installed Python 3 and is worked properly, here is simple commands to start.


import this in Python 3

Start the python3 then type import this, and you should get the output below.

Basically is a "best practices" for coding.

import this 
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

ask for help in Python 3

The help() command will be like a manual and samples commands

help()

Welcome to Python 3.8's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.8/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

List available modules in Python 3 with help command

After executing help(), simply type modules.

help> modules

Please wait a moment while I gather a list of all available modules...

IPython             _tracemalloc        gzip                secrets
__future__          _uuid               hashlib             select
_abc                _warnings           heapq               selectors
_ast                _weakref            hmac                shelve
_asyncio            _weakrefset         html                shlex
_bisect             _xxsubinterpreters  http                shutil
_blake2             _xxtestfuzz         imaplib             signal
_bootlocale         abc                 imghdr              site
_bz2                aifc                imp                 sitecustomize
_codecs             antigravity         importlib           six
_codecs_cn          argparse            inspect             smtpd
_codecs_hk          array               io                  smtplib
_codecs_iso2022     ast                 ipaddress           sndhdr
_codecs_jp          asynchat            ipython_genutils    socket
_codecs_kr          asyncio             itertools           socketserver
_codecs_tw          asyncore            jedi                spwd
_collections        atexit              json                sqlite3
_collections_abc    audioop             keyword             sre_compile
_compat_pickle      autoreload          linecache           sre_constants
_compression        backcall            locale              sre_parse
_contextvars        base64              logging             ssl
_crypt              bdb                 lzma                stat
_csv                binascii            mailbox             statistics
_ctypes             binhex              mailcap             storemagic
_ctypes_test        bisect              marshal             string
_curses             builtins            math                stringprep
_curses_panel       bz2                 mimetypes           struct
_datetime           cProfile            mmap                subprocess
_dbm                calendar            modulefinder        sunau
_decimal            cgi                 multiprocessing     symbol
_dummy_thread       cgitb               netrc               sympyprinting
_elementtree        chunk               nis                 symtable
_functools          cmath               nntplib             sys
_hashlib            cmd                 ntpath              sysconfig
_heapq              code                nturl2path          syslog
_imp                codecs              numbers             tabnanny
_io                 codeop              opcode              tarfile
_json               collections         operator            telnetlib
_locale             colorsys            optparse            tempfile
_lsprof             compileall          os                  termios
_lzma               concurrent          ossaudiodev         test
_markupbase         configparser        parser              tests
_md5                contextlib          parso               textwrap
_multibytecodec     contextvars         pathlib             this
_multiprocessing    copy                pdb                 threading
_opcode             copyreg             pexpect             time
_operator           crypt               pickle              timeit
_osx_support        csv                 pickleshare         token
_pickle             ctypes              pickletools         tokenize
_posixshmem         curses              pipes               trace
_posixsubprocess    cythonmagic         pkg_resources       traceback
_py_abc             dataclasses         pkgutil             tracemalloc
_pydecimal          datetime            platform            traitlets
_pyio               dbm                 plistlib            tty
_queue              decimal             poplib              turtle
_random             decorator           posix               types
_sha1               difflib             posixpath           typing
_sha256             dis                 pprint              unicodedata
_sha3               distutils           profile             unittest
_sha512             doctest             prompt_toolkit      urllib
_signal             dummy_threading     pstats              uu
_sitebuiltins       email               pty                 uuid
_socket             encodings           ptyprocess          venv
_sqlite3            enum                pwd                 warnings
_sre                errno               py_compile          wave
_ssl                faulthandler        pyclbr              wcwidth
_stat               fcntl               pydoc               weakref
_statistics         filecmp             pydoc_data          webbrowser
_string             fileinput           pyexpat             wsgiref
_strptime           fnmatch             pygments            xdrlib
_struct             formatter           queue               xml
_symtable           fractions           quopri              xmlrpc
_sysconfigdata__linux_x86_64-linux-gnu ftplib              random              xxlimited
_sysconfigdata__x86_64-linux-gnu functools           re                  xxsubtype
_testbuffer         gc                  readline            zipapp
_testcapi           genericpath         reprlib             zipfile
_testimportmultiple getopt              resource            zipimport
_testinternalcapi   getpass             rlcompleter         zlib
_testmultiphase     gettext             rmagic              
_thread             glob                runpy               
_threading_local    grp                 sched               

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".

help> 

List available TOPICS in Python 3 with help command

help> topics

Here is a list of available topics.  Enter any topic name to get more help.

ASSERTION           DELETION            LOOPING             SHIFTING
ASSIGNMENT          DICTIONARIES        MAPPINGMETHODS      SLICINGS
ATTRIBUTEMETHODS    DICTIONARYLITERALS  MAPPINGS            SPECIALATTRIBUTES
ATTRIBUTES          DYNAMICFEATURES     METHODS             SPECIALIDENTIFIERS
AUGMENTEDASSIGNMENT ELLIPSIS            MODULES             SPECIALMETHODS
BASICMETHODS        EXCEPTIONS          NAMESPACES          STRINGMETHODS
BINARY              EXECUTION           NONE                STRINGS
BITWISE             EXPRESSIONS         NUMBERMETHODS       SUBSCRIPTS
BOOLEAN             FLOAT               NUMBERS             TRACEBACKS
CALLABLEMETHODS     FORMATTING          OBJECTS             TRUTHVALUE
CALLS               FRAMEOBJECTS        OPERATORS           TUPLELITERALS
CLASSES             FRAMES              PACKAGES            TUPLES
CODEOBJECTS         FUNCTIONS           POWER               TYPEOBJECTS
COMPARISON          IDENTIFIERS         PRECEDENCE          TYPES
COMPLEX             IMPORTING           PRIVATENAMES        UNARY
CONDITIONAL         INTEGER             RETURNING           UNICODE
CONTEXTMANAGERS     LISTLITERALS        SCOPING             
CONVERSIONS         LISTS               SEQUENCEMETHODS     
DEBUGGING           LITERALS            SEQUENCES           

help> 

ask for help on a specific module

help> http		
Help on package http:

NAME
    http

MODULE REFERENCE
    https://docs.python.org/3.8/library/http
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

PACKAGE CONTENTS
    client
    cookiejar
    cookies
    server

CLASSES
    enum.IntEnum(builtins.int, enum.Enum)
        HTTPStatus
        (....)

you get the idea...


use dir in Python 3 to see what is available on the module

import http

dir(http)

['HTTPStatus',
 'IntEnum',
 '__all__',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__path__',
 '__spec__',
 'client']

use type to confirm the type of variable

var1 = 'a'
var2 = 1
var3 = ('a','b','c')
var4 = ['a','b','c']
var5={'Website':'AntonioFeijao.com','LinkedIn':'AntonioFeijaoUK'}                     

type(var1)
str

type(var2)
int

type(var3)
tuple

type(var4)
list

type(var5)
dict

Conclusion

On this page I mentioned : * import this * help() * help> modules * help> topics * help> http * dir(imported_module) * type(var...)

I hope these tips will help you explore Python 3 further and at the same time having some fun.

There are, of course various free resources online,
for example this one https://www.tutorialspoint.com/python3/index.htm .

Have fun learning,

Antonio Feijao

Python3 create and active a python virtual environment

Intro to Python3 environments

While using Python, you might want to use a separate environment to keep pip packages separate from other environments
or separate from your main operation system.

Python virtual environments is on of the options for that.
Of course you could use containers but here I just want a quick and simple virtual environment to run python code.

Official page and documentation https://docs.python.org/3/library/venv.html

Python 3 creating a virtual environment

python3 -m venv /path/to/new/virtual/environment

-m use for python module venv virtual environment module /path/to/new/virtual/environment folder/directory for the virtual environment


Python 3 activating a virtual environment

source <venv>/bin/activate


Happy learning!

Antonio Feijao UK