• Skip to main content

Uly.me

cloud engineer

  • Home
  • About
  • Archives

python

Python Web Server

May 20, 2022

Here’s a quick way to start a web server using Python (not recommended for production).

If you want to use python3, you may have to use explicitly use python3.

Check what versions you have first.

python --version
python3 --version

python --version python3 --version

Start web server using port 8080 in the current directory.

python -m http.server 8080

python -m http.server 8080

If you want an alternate directory, use this -d option.

python -m http.server 8080 -d /tmp

python -m http.server 8080 -d /tmp

It’s a great tool for quick downloads.

Filed Under: Linux Tagged With: download, python, server, web

Python Boto3 S3 List Objects

February 27, 2022

How to list S3 objects using Python Boto3

import boto3
from sys import argv
bucket=argv[1]
s3 = boto3.resource('s3')
mybucket = s3.Bucket(bucket)
def list_buckets():
    print("List of Buckets: ")
    for bucket in s3.buckets.all():
        print(bucket.name)
def list_files():
    print("Buckets: The objects in the \"" + bucket + "\" buckets are ... ")
    for files in mybucket.objects.all():
        print(files.key)
def main():
    #list_buckets()
    list_files()
if __name__ == "__main__":
    main()

import boto3 from sys import argv bucket=argv[1] s3 = boto3.resource('s3') mybucket = s3.Bucket(bucket) def list_buckets(): print("List of Buckets: ") for bucket in s3.buckets.all(): print(bucket.name) def list_files(): print("Buckets: The objects in the \"" + bucket + "\" buckets are ... ") for files in mybucket.objects.all(): print(files.key) def main(): #list_buckets() list_files() if __name__ == "__main__": main()

Running command

$ python test.py bucket-name    # with python
$ ./test.py bucket-name         # without python

$ python test.py bucket-name # with python $ ./test.py bucket-name # without python

Results

Buckets: The objects in the "bucket-name" are ....
abc.txt
def.txt

Buckets: The objects in the "bucket-name" are .... abc.txt def.txt

Filed Under: Linux Tagged With: boto3, list, objects, python, s3

Python Virtual Environment

February 27, 2022

How to create a Python virtual environment.

On Windows

$ pip install venv
$ python3 -m venv ~/python-test

$ pip install venv $ python3 -m venv ~/python-test

On Ubuntu

$ sudo apt install python3.8-venv
$ python3 -m venv ~/python-test

$ sudo apt install python3.8-venv $ python3 -m venv ~/python-test

On Mac OS

$ brew install virtualenv
$ virtualenv python-test

$ brew install virtualenv $ virtualenv python-test

Activate

$ cd ~/python-test
$ source bin/activate

$ cd ~/python-test $ source bin/activate

Deactivate

$ deactivate

$ deactivate

Filed Under: Linux Tagged With: activate, deactivate, environment, python, virtual

Json Formatter

January 12, 2022

If you have a json file that needs formatting, you can use a built-in tool in Python.

python -m json.tool sample.json

python -m json.tool sample.json

Output will be printed on screen. You can also send the output to a file.

python -m json.tool sample.json > sample2.json

python -m json.tool sample.json > sample2.json

Filed Under: Linux Tagged With: formatter, json, python

Fibonacci Sequence in Python

December 3, 2021

How to calculate Fibonacci sequence in Python.

Create a file called fib.py.

nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
    print("Please enter a positive integer")
elif nterms == 1:
    print("Fibonacci sequence:")
    print(n1)
else:
    print("Fibonacci sequence:")
    while count < nterms:
        print(n1)
        nth = n1 + n2
        # update values
        n1 = n2
        n2 = nth
        count += 1

nterms = int(input("How many terms? ")) n1, n2 = 0, 1 count = 0 if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibonacci sequence:") print(n1) else: print("Fibonacci sequence:") while count < nterms: print(n1) nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1

Run it.

$ python fib.py
How many terms? 5
Fibonacci sequence:
0
1
1
2
3

$ python fib.py How many terms? 5 Fibonacci sequence: 0 1 1 2 3

Again.

$ python fib.py
How many terms? 10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

$ python fib.py How many terms? 10 Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34

Filed Under: Linux Tagged With: fibonacci, math, python, sequence

Python Pythagorean Theorem

February 9, 2020

Here’s a simple Python program that calculates the hypotenuse of a right angle triangle using the Pythagorean Theory.

a2 + b2 = c2

#!/usr/local/bin/python3
import math
print("================================================")
print("This program will calculate pythagorean theorem.")
print("================================================")
side_A = float(input("Enter side A: "))
side_B = float(input("Enter side B: "))
def pythagoreamTherem(side_A, side_B):
	side_C = math.sqrt(side_A * side_A + side_B * side_B)
	return side_C
side_C = pythagoreamTherem(side_A, side_B)
print("")
print("Side C is: " + "%.2f" % round(side_C,2))
print("")

#!/usr/local/bin/python3 import math print("================================================") print("This program will calculate pythagorean theorem.") print("================================================") side_A = float(input("Enter side A: ")) side_B = float(input("Enter side B: ")) def pythagoreamTherem(side_A, side_B): side_C = math.sqrt(side_A * side_A + side_B * side_B) return side_C side_C = pythagoreamTherem(side_A, side_B) print("") print("Side C is: " + "%.2f" % round(side_C,2)) print("")

Output

ulysses@penguin:~/home/user$ python3 pythagorean.py 
================================================
This program will calculate pythagorean theorem.
================================================
Enter side A: 3
Enter side B: 4
 
Side C is: 5.00

ulysses@penguin:~/home/user$ python3 pythagorean.py ================================================ This program will calculate pythagorean theorem. ================================================ Enter side A: 3 Enter side B: 4 Side C is: 5.00

Filed Under: Linux Tagged With: hypotenuse, math, pythagorean theorem, python, right angle, triangle

IAM List Access Keys

January 14, 2020

Here’s how to list all the access keys in AWS via Python.

import logging
import boto3
from botocore.exceptions import ClientError
 
# set aws profile
session = boto3.Session(profile_name="default")
 
# get list of users
 
iam = session.client('iam')
users = iam.list_users()
 
# display results
print("{0:<20} {1:<25} {2:<15} {3:<10}".format('UserName', 'AccessKey', 'Status', 'CreateDate'))
print("----------------------------------------------------------------------------------------")
 
for a in users['Users']:
    user = a['UserName']
    # get keys
    keys = iam.list_access_keys(UserName=user)
    for b in keys['AccessKeyMetadata']:
        username = b['UserName']
        accesskeyid = b['AccessKeyId']
        status = b['Status']
        createdate = str(b['CreateDate'])
        print("{0:<20} {1:<25} {2:<15} {3:<10}".format(username, accesskeyid, status, createdate))

import logging import boto3 from botocore.exceptions import ClientError # set aws profile session = boto3.Session(profile_name="default") # get list of users iam = session.client('iam') users = iam.list_users() # display results print("{0:<20} {1:<25} {2:<15} {3:<10}".format('UserName', 'AccessKey', 'Status', 'CreateDate')) print("----------------------------------------------------------------------------------------") for a in users['Users']: user = a['UserName'] # get keys keys = iam.list_access_keys(UserName=user) for b in keys['AccessKeyMetadata']: username = b['UserName'] accesskeyid = b['AccessKeyId'] status = b['Status'] createdate = str(b['CreateDate']) print("{0:<20} {1:<25} {2:<15} {3:<10}".format(username, accesskeyid, status, createdate))

Filed Under: Cloud, Linux Tagged With: aws, boto3, cli, create, iam, keys, list, python, time, user

AWS Boto3 Client

January 9, 2020

Boto is the Amazon Web Services (AWS) SDK for Python. It enables Python developers to create, configure, and manage AWS services, such as EC2 and S3. Boto provides an easy to use, object-oriented API, as well as low-level access to AWS services.

Here’s a quick example how to query for AWS resources.

import logging
import boto3
from botocore.exceptions import ClientError
 
# set aws profile
session = boto3.Session(profile_name="default")
 
# get buckets
s3 = session.client('s3')
results = s3.list_buckets()
 
# display buckets
print('Existing buckets:')
for key in results['Buckets']:
    print(f'{key["Name"]}')
 
# get ec2 instances. set region.
ec2 = session.client('ec2', region_name='us-east-1')
results = ec2.describe_instances()
 
# display instances
for key in results["Reservations"]:
      for instance in key["Instances"]:
           instance_id = instance["InstanceId"]
           instance_type = instance["InstanceType"]
           availability_zone = instance["Placement"]["AvailabilityZone"]
           print(instance_id + "\t" + instance_type + "\t" + availability_zone)
 
# get list of users
client = session.client('iam')
results = client.list_users()
 
# display list of users
for key in results['Users']:
    print (key['UserName'])

import logging import boto3 from botocore.exceptions import ClientError # set aws profile session = boto3.Session(profile_name="default") # get buckets s3 = session.client('s3') results = s3.list_buckets() # display buckets print('Existing buckets:') for key in results['Buckets']: print(f'{key["Name"]}') # get ec2 instances. set region. ec2 = session.client('ec2', region_name='us-east-1') results = ec2.describe_instances() # display instances for key in results["Reservations"]: for instance in key["Instances"]: instance_id = instance["InstanceId"] instance_type = instance["InstanceType"] availability_zone = instance["Placement"]["AvailabilityZone"] print(instance_id + "\t" + instance_type + "\t" + availability_zone) # get list of users client = session.client('iam') results = client.list_users() # display list of users for key in results['Users']: print (key['UserName'])

Filed Under: Cloud Tagged With: aws, boto3, cli, ec2, iam, python, s3, sdk

  • Go to page 1
  • Go to page 2
  • Go to Next Page »
  • Home
  • About
  • Archives

Copyright © 2023