Skip to content

Latest commit

 

History

History
292 lines (203 loc) · 3.97 KB

File metadata and controls

292 lines (203 loc) · 3.97 KB

Script Structure With main() And sys.argv

import sys


def main():
    if len(sys.argv) != 3:
        print(f"Usage: {sys.argv[0]} INPUT OUTPUT")
        return 1

    input_file = sys.argv[1]
    output_file = sys.argv[2]

    with open(input_file, "rt") as f:
        with open(output_file, "wt") as out:
            for line in f:
                line = line.strip()

                if not line:
                    continue

                print(line, file=out)

    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Run:

python3 script.py input.txt output.txt

1. Read A Text File Line By Line

with open("input.txt", "rt") as file:
    for line in file:
        line = line.strip()

        if not line:
            continue

        print(line)

Input:

192.168.1.10

8.8.8.8

Output:

192.168.1.10
8.8.8.8

2. Write Output To A File

lines = ["Report", "------", "Everything is under control."]

with open("report.txt", "wt") as file:
    for line in lines:
        print(line, file=file)

Output file:

Report
------
Everything is under control.

3. Read A CSV File

import csv

with open("data.csv", "rt") as file:
    reader = csv.DictReader(file)

    for row in reader:
        host = row["host"]
        port = int(row["port"])
        status = row["status"]

        print(host, port, status)

CSV input:

host,port,status
web01,443,open
db01,5432,closed

Output:

web01 443 open
db01 5432 closed

4. Build A Lookup Dictionary

import csv

lookup = {}

with open("labels.csv", "rt") as file:
    rows = csv.DictReader(file)

    for row in rows:
        lookup[row["ip"]] = row["label"]

print(lookup.get("8.8.8.8", "UNKNOWN"))
print(lookup.get("192.168.1.10", "UNKNOWN"))

CSV input:

ip,label
8.8.8.8,Google DNS
1.1.1.1,Cloudflare DNS

Output:

Google DNS
UNKNOWN

5. Count Occurrences

counts = {}
items = ["admin", "root", "admin", "test", "admin"]

for item in items:
    counts[item] = counts.get(item, 0) + 1

print(counts)

Output:

{'admin': 3, 'root': 1, 'test': 1}

6. Group Values Per Key

services_by_host = {}

rows = [
    ("web01", "22/tcp"),
    ("web01", "443/tcp"),
    ("db01", "5432/tcp"),
]

for host, service in rows:
    services_by_host.setdefault(host, []).append(service)

print(services_by_host)

Output:

{'web01': ['22/tcp', '443/tcp'], 'db01': ['5432/tcp']}

7. Lists, Tuples, Dictionaries

Use a list for many items:

ips = ["8.8.8.8", "1.1.1.1", "8.8.8.8"]

for ip in ips:
    print(ip)

Use a tuple for one fixed record:

record = ("8.8.8.8", "Google DNS", "low")

ip, label, risk = record

print(ip)
print(label)
print(risk)

Use a dictionary for lookup:

labels = {
    "8.8.8.8": "Google DNS",
    "1.1.1.1": "Cloudflare DNS",
}

label = labels.get("9.9.9.9", "UNKNOWN")
print(label)

8. Sort By Count

failed_by_ip = {
    "203.0.113.10": 6,
    "198.51.100.7": 2,
    "203.0.113.11": 3,
}

for ip, count in sorted(failed_by_ip.items(), key=lambda item: (-item[1], item[0])):
    print(ip, count)

Output:

203.0.113.10 6
203.0.113.11 3
198.51.100.7 2

9. Command-Line Arguments

import sys

if len(sys.argv) != 3:
    print(f"Usage: {sys.argv[0]} INPUT OUTPUT")
    sys.exit(1)

input_file = sys.argv[1]
output_file = sys.argv[2]

print("Input:", input_file)
print("Output:", output_file)

Run:

python3 script.py auth.log auth_report.txt

Output:

Input: auth.log
Output: auth_report.txt

10. When To Use What

list        = many items in order
tuple       = one fixed record with multiple parts
dictionary  = lookup table: key -> value

Examples:

ips = ["8.8.8.8", "1.1.1.1"]

record = ("8.8.8.8", "Google DNS", "low")

labels = {
    "8.8.8.8": "Google DNS",
    "1.1.1.1": "Cloudflare DNS",
}