<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Luffytaroouu on Medium]]></title>
        <description><![CDATA[Stories by Luffytaroouu on Medium]]></description>
        <link>https://medium.com/@aa2812061?source=rss-a4dad81bab85------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WHhnoLQsgOInoKQD</url>
            <title>Stories by Luffytaroouu on Medium</title>
            <link>https://medium.com/@aa2812061?source=rss-a4dad81bab85------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:38:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aa2812061/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Phonebook in Python: A Beginner’s Walkthrough]]></title>
            <link>https://medium.com/@aa2812061/building-a-phonebook-in-python-a-beginners-walkthrough-5938fb27f303?source=rss-a4dad81bab85------2</link>
            <guid isPermaLink="false">https://medium.com/p/5938fb27f303</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[phonebooks]]></category>
            <dc:creator><![CDATA[Luffytaroouu]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 01:37:59 GMT</pubDate>
            <atom:updated>2026-10-13T01:37:59.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnNNC1HoFq9kQNMrQWyM3w.png" /></figure><p>I remembered a couple of beginner projects back in college that we were made to do to understand a programming language, and some I recall were building a calculator and building a phonebook. So, I had a long weekend and some extra time in hand, and I thought why not build a phonebook, so I could recall some of the things I did back in my undergrad. Again, I don’t really use Python a lot, but I have been relearning it, and I wanted to write the program the best I could recall, without looking anything up first.</p><p>The idea was straightforward: a command-line program where a user can add a contact, delete one, search for one, view the whole list, or edit an existing entry, all stored and manipulated while the program runs.</p><p>Here’s the first draft I built :</p><blockquote>(I still don’t have a habit of writing comments, so forgive me for that):</blockquote><pre><br>print (&quot;++ Welcome inside the phonebook. What would you like to do? ++&quot;)<br><br>book = {}<br>while True:<br>    <br>    print (&quot;\n1: To Add Contact&quot;)<br>    print (&quot;2: To Delete Contact&quot;)<br>    print (&quot;3: To Search Contacts&quot;)<br>    print (&quot;4: To view the whole contact book&quot;)<br>    print (&quot;5: To edit the phonebook&quot;)<br>    print (&quot;6: To quit the phonebook&quot;)<br>    question = input(&quot;Please input which option you want, 1, 2, 3, 4, 5, or 6: &quot;)<br>    print (&quot; &quot;)<br>    if question == &quot;1&quot;:<br>        name = input (&quot;Enter the name of the person: &quot;).lower()<br>        email = input (&quot;Enter the email address of the person: &quot;)<br>        number = input (&quot;Enter the number of the person: &quot;)<br>        address = input (&quot;Enter the address of the person: &quot;)<br>        birthday = input (&quot;Enter the birthday of the person: &quot;)<br>        location = input (&quot;Enter the location of the person: &quot;)<br><br>        book[name] = {<br>            &quot;number&quot;: number,<br>            &quot;email&quot;: email,<br>            &quot;address&quot;: address,<br>            &quot;birthday&quot;: birthday,<br>            &quot;location&quot;: location<br>        }<br>        print (f&quot;The contact for {name.title()} was added sucessfully&quot;)<br><br><br>        <br>    elif question == &quot;2&quot;:<br>        name = input (&quot;Enter the name of the person whose contact you want to delete: &quot;).lower()<br>        try:<br>            del book[name]<br>            print (f&quot;The contact for {name.title()} was deleted sucessfully&quot;)<br>        except:<br>            print (&quot;The name doesnt exist&quot;)<br><br><br>    <br>    elif question == &quot;3&quot;:<br>        name = input (&quot;Enter the name of the person whose contact you are looking for: &quot;).lower()<br>        try:<br>            user = book[name]<br>            print (f&quot;The details for the user {name.title()} are as follows: &quot;)<br>            print (f&quot;Phone number: {user[&#39;number&#39;]}&quot;)<br>            print (f&quot;Email: {user[&#39;email&#39;]}&quot;)<br>            print (f&quot;Address: {user[&#39;address&#39;]}&quot;)<br>            print (f&quot;Birthday: {user[&#39;birthday&#39;]}&quot;)<br>            print (f&quot;Location: {user[&#39;location&#39;]}&quot;)<br><br>        except KeyError:<br>            print (&quot;The name you looked for doesnt exist&quot;)<br><br><br><br>    elif question == &quot;4&quot;:<br>        for item in book:<br>            user = book[item]<br>            print (f&quot;Name: {item. title()}&quot;)<br>            print (f&quot;Phone number: {user[&#39;number&#39;]}&quot;)<br>            print (f&quot;Email: {user[&#39;email&#39;]}&quot;)<br>            print (f&quot;Address: {user[&#39;address&#39;]}&quot;)<br>            print (f&quot;Birthday: {user[&#39;birthday&#39;]}&quot;)<br>            print (f&quot;Location: {user[&#39;location&#39;]}&quot;)<br><br><br><br>    elif question == &quot;5&quot;:<br>        name = input (&quot;Enter the name of the person: &quot;).lower()<br>        if name in book:<br>            email = input (&quot;Enter the email address of the person: &quot;)<br>            number = input (&quot;Enter the number of the person: &quot;)<br>            address = input (&quot;Enter the address of the person: &quot;)<br>            birthday = input (&quot;Enter the birthday of the person: &quot;)<br>            location = input (&quot;Enter the location of the person: &quot;)<br><br>            book[name] = {<br>                &quot;number&quot;: number,<br>                &quot;email&quot;: email,<br>                &quot;address&quot;: address,<br>                &quot;birthday&quot;: birthday,<br>                &quot;location&quot;: location<br>            }<br>            print (f&quot;The contact for {name.title()} was edited sucessfully&quot;)<br>        else:<br>            print(&quot;The user doesnt exist&quot;)<br><br><br><br>    elif question == &quot;6&quot;:<br>        break<br><br>    else:<br>        print (&quot;Sorry please choose an option from within 1,2,3,4,5, or 6&quot;)</pre><p>Walking through my own thinking at the time:</p><p><strong>Why a dictionary, not a list.</strong> A list felt like the obvious first instinct for “a bunch of contacts,” but a list is really just an ordered collection; there’s no natural way to look someone up by name without looping through the whole thing every time. What I actually wanted was closer to a lookup table: give me a name, get me back that person’s details. A dictionary does exactly that. So I made each contact’s name the key, and the value another, smaller dictionary holding their number, email, address, birthday, and location.</p><p><strong>Lowercasing on the way in, title-casing on the way out.</strong> Since dictionary keys are case-sensitive, “John” and “john” would otherwise be treated as two completely different people. So every name gets .lower()’d before it’s used as a key or looked up, which means the user can type a name however they want and it’ll still match. For display, I used .title() only at print time, so the user still sees “John” in the output, even though internally it’s stored lowercase.</p><p><strong>One loop, one long if/elif chain.</strong> Since the program needed to keep running and let the user repeat actions, the whole thing lives inside a while True: loop, with each menu option as its own branch, and the loop only breaks when the user chooses to quit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*RWeNxRiy_eewXTt3mQQtqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*dOc1eXJ9pGEhTa6ZHTmYyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*6yjacpFTmdlGS1t7irjvdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*dvfGtXcmmg3qQL-WaR3dLA.png" /></figure><p><strong>Adding persistence</strong></p><p>The first draft worked, but only while the program was running. Close it, and the entire phonebook vanished, since everything only ever lived in a plain dictionary in memory. For something called a “phonebook,” that’s a pretty significant gap; a real phonebook is supposed to still be there tomorrow.</p><p>The fix was to save the dictionary to a file on disk, and load it back in when the program starts. Python’s built-in json module handles this well, since a dictionary of dictionaries maps almost directly onto JSON’s own structure.</p><pre><br>import json  # Import the built-in library to read/write files<br>import os    # Import os to check if the file already exists<br><br># 1. LOAD DATA: Check if the file exists and load it automatically<br>file_name = &quot;phonebook.json&quot;<br><br>if os.path.exists(file_name):<br>    try:<br>        with open(file_name, &quot;r&quot;) as file:<br>            book = json.load(file)<br>        print(&quot;++ Welcome back! Phonebook data loaded successfully. ++&quot;)<br>    except json.JSONDecodeError:<br>        print(&quot;++ Welcome inside the phonebook. (Saved file was corrupted, starting fresh) ++&quot;)<br>        book = {}<br>else:<br>    print(&quot;++ Welcome inside the phonebook. What would you like to do? ++&quot;)<br>    book = {}<br><br><br># Helper function to save data instantly after changes<br>def save_phonebook():<br>    with open(file_name, &quot;w&quot;) as file:<br>        json.dump(book, file, indent=4)  # indent=4 makes the file easy for humans to read<br><br><br>while True:<br>    print(&quot;\n1: To Add Contact&quot;)<br>    print(&quot;2: To Delete Contact&quot;)<br>    print(&quot;3: To Search Contacts&quot;)<br>    print(&quot;4: To view the whole contact book&quot;)<br>    print(&quot;5: To edit the phonebook&quot;)<br>    print(&quot;6: To quit the phonebook&quot;)<br>    question = input(&quot;Please input which option you want, 1, 2, 3, 4, 5, or 6: &quot;)<br>    print(&quot; &quot;)<br>    <br>    if question == &quot;1&quot;:<br>        name = input(&quot;Enter the name of the person: &quot;).lower()<br>        email = input(&quot;Enter the email address of the person: &quot;)<br>        number = input(&quot;Enter the number of the person: &quot;)<br>        address = input(&quot;Enter the address of the person: &quot;)<br>        birthday = input(&quot;Enter the birthday of the person: &quot;)<br>        location = input(&quot;Enter the location of the person: &quot;)<br><br>        book[name] = {<br>            &quot;number&quot;: number,<br>            &quot;email&quot;: email,<br>            &quot;address&quot;: address,<br>            &quot;birthday&quot;: birthday,<br>            &quot;location&quot;: location<br>        }<br>        save_phonebook()  # Save changes to the file!<br>        print(f&quot;The contact for {name.title()} was added successfully&quot;)<br><br>    elif question == &quot;2&quot;:<br>        name = input(&quot;Enter the name of the person whose contact you want to delete: &quot;).lower()<br>        try:<br>            del book[name]<br>            save_phonebook()  # Save changes to the file!<br>            print(f&quot;The contact for {name.title()} was deleted successfully&quot;)<br>        except KeyError:<br>            print(&quot;The name doesnt exist&quot;)<br><br>    elif question == &quot;3&quot;:<br>        name = input(&quot;Enter the name of the person whose contact you are looking for: &quot;).lower()<br>        try:<br>            user = book[name]<br>            print(f&quot;The details for the user {name.title()} are as follows: &quot;)<br>            print(f&quot;Phone number: {user[&#39;number&#39;]}&quot;)<br>            print(f&quot;Email: {user[&#39;email&#39;]}&quot;)<br>            print(f&quot;Address: {user[&#39;address&#39;]}&quot;)<br>            print(f&quot;Birthday: {user[&#39;birthday&#39;]}&quot;)<br>            print(f&quot;Location: {user[&#39;location&#39;]}&quot;)<br>        except KeyError:<br>            print(&quot;The name you looked for doesnt exist&quot;)<br><br>    elif question == &quot;4&quot;:<br>        if not book:<br>            print(&quot;The phonebook is currently empty.&quot;)<br>        else:<br>            for item in book:<br>                user = book[item]<br>                print(f&quot;Name: {item.title()}&quot;)<br>                print(f&quot;Phone number: {user[&#39;number&#39;]}&quot;)<br>                print(f&quot;Email: {user[&#39;email&#39;]}&quot;)<br>                print(f&quot;Address: {user[&#39;address&#39;]}&quot;)<br>                print(f&quot;Birthday: {user[&#39;birthday&#39;]}&quot;)<br>                print(f&quot;Location: {user[&#39;location&#39;]}&quot;)<br>                print(&quot;------------------------&quot;)<br><br>    elif question == &quot;5&quot;:<br>        name = input(&quot;Enter the name of the person: &quot;).lower()<br>        if name in book:<br>            email = input(&quot;Enter the email address of the person: &quot;)<br>            number = input(&quot;Enter the number of the person: &quot;)<br>            address = input(&quot;Enter the address of the person: &quot;)<br>            birthday = input(&quot;Enter the birthday of the person: &quot;)<br>            location = input(&quot;Enter the location of the person: &quot;)<br><br>            book[name] = {<br>                &quot;number&quot;: number,<br>                &quot;email&quot;: email,<br>                &quot;address&quot;: address,<br>                &quot;birthday&quot;: birthday,<br>                &quot;location&quot;: location<br>            }<br>            save_phonebook()  # Save changes to the file!<br>            print(f&quot;The contact for {name.title()} was edited successfully&quot;)<br>        else:<br>            print(&quot;The user doesnt exist&quot;)<br><br>    elif question == &quot;6&quot;:<br>        print(&quot;Goodbye!&quot;)<br>        break<br><br>    else:<br>        print(&quot;Sorry please choose an option from within 1,2,3,4,5, or 6&quot;)</pre><p>A few things worth calling out here:</p><ul><li><strong>os.path.exists(file_name)</strong> checks whether a save file is even there before trying to open it. First run, there’s nothing to load, so it just starts with an empty phonebook instead of crashing trying to open a file that doesn’t exist yet.</li><li><strong>The </strong><strong>try/except json.JSONDecodeError</strong> covers a case I hadn’t thought about until I ran into it: what if the file exists, but isn’t valid JSON, say because the program crashed mid-write once, or I manually edited it and broke the formatting? Instead of the whole program dying on startup, it falls back to starting fresh.</li></ul><p>Saving itself got pulled into its own function, rather than repeating the save logic in three different places (add, delete, edit):</p><pre>def save_phonebook():<br>    with open(file_name, &quot;w&quot;) as file:<br>        json.dump(book, file, indent=4)</pre><p>json.dump writes the dictionary straight to a file in JSON format. indent=4 isn’t required, it just pretty-prints the file with indentation, so if I ever open phonebook.json directly to look at it, it’s actually readable rather than one long unbroken line.</p><p>From there, every action that changes the data, adding, deleting, or editing a contact, just calls save_phonebook() right after making the change, so the file on disk never falls out of sync with what’s in memory.</p><p><strong>Renaming </strong><strong>list to </strong><strong>book</strong></p><p>The earlier draft used list as the variable name for the phonebook itself, which was a mistake I didn’t catch at the time: list is already a built-in Python type, so naming a variable that steps on it, and anywhere else in the program that might have needed the real list() function would’ve broken silently. Renaming it to book fixed that, and honestly reads more clearly anyway, since it’s a phonebook, not a generic list.</p><p><strong>Tightening up the delete exception</strong></p><p>The first draft caught delete failures with a bare except:, which catches literally any error, not just “this name wasn’t found.” Since I know exactly what can go wrong here, trying to delete a key that doesn’t exist raises a KeyError, I narrowed it to except KeyError: specifically, matching what the search option was already doing.</p><p><strong>Handling an empty phonebook on view</strong></p><p>Option 4 originally had no check for an empty phonebook; if there were no contacts yet, the loop just silently did nothing, and the user got no feedback at all. Now it checks if not book: first and tells the user the phonebook is empty, rather than leaving them staring at a blank response wondering if something broke.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*9eWhJhsLZvbHwK1aDSjAlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*4qDHB19UoAlM1mXNHEFyhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*9Cn_vKO-kY3TaDWQFEbjFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*ynn50gtxdG3sOX3uh3XF3g.png" /></figure><p><strong>Validating the input</strong></p><p>Up to this point, the phonebook accepted literally anything typed in for email, phone number, or birthday, there was nothing stopping someone from entering “banana” as a phone number. The next thing I wanted to add was actual validation on three fields: email, phone number, and birthday.</p><pre><br>import json<br>import os<br>import re<br><br>file_name = &quot;phonebook.json&quot;<br><br>def validate_email(email):<br>    pattern = r&quot;^[\w\.-]+@[\w\.-]+\.\w+$&quot;<br>    return re.match(pattern, email) is not None<br><br>def validate_phone(number):<br>    return number.isdigit() and len(number) == 10<br><br>def validate_birthday(birthday):<br>    parts = birthday.split(&quot;/&quot;)<br>    if len(parts) != 3:<br>        return False<br>    month, day, year = parts<br>    if not (month.isdigit() and day.isdigit() and year.isdigit()):<br>        return False<br>    month, day, year = int(month), int(day), int(year)<br>    if not (1 &lt;= month &lt;= 12):<br>        return False<br>    if not (1 &lt;= day &lt;= 31):<br>        return False<br>    if len(str(year)) != 4:<br>        return False<br>    return True<br><br>def get_valid_email():<br>    while True:<br>        email = input(&quot;Enter the email address of the person: &quot;)<br>        if validate_email(email):<br>            return email<br>        print(&quot;That doesn&#39;t look like a valid email. Try again (e.g. name@example.com)&quot;)<br><br>def get_valid_phone():<br>    while True:<br>        number = input(&quot;Enter the number of the person (10 digits): &quot;)<br>        if validate_phone(number):<br>            return number<br>        print(&quot;Phone number must be exactly 10 digits, numbers only.&quot;)<br><br>def get_valid_birthday():<br>    while True:<br>        birthday = input(&quot;Enter the birthday of the person (MM/DD/YYYY): &quot;)<br>        if validate_birthday(birthday):<br>            return birthday<br>        print(&quot;Birthday must be in MM/DD/YYYY format, with a valid month and day.&quot;)<br><br>if os.path.exists(file_name):<br>    try:<br>        with open(file_name, &quot;r&quot;) as file:<br>            book = json.load(file)<br>        print(&quot;++ Welcome back! Phonebook data loaded successfully. ++&quot;)<br>    except json.JSONDecodeError:<br>        print(&quot;++ Welcome inside the phonebook. (Saved file was corrupted, starting fresh) ++&quot;)<br>        book = {}<br>else:<br>    print(&quot;++ Welcome inside the phonebook. What would you like to do? ++&quot;)<br>    book = {}<br><br>def save_phonebook():<br>    with open(file_name, &quot;w&quot;) as file:<br>        json.dump(book, file, indent=4)<br><br>while True:<br>    print(&quot;\n1: To Add Contact&quot;)<br>    print(&quot;2: To Delete Contact&quot;)<br>    print(&quot;3: To Search Contacts&quot;)<br>    print(&quot;4: To view the whole contact book&quot;)<br>    print(&quot;5: To edit the phonebook&quot;)<br>    print(&quot;6: To quit the phonebook&quot;)<br>    question = input(&quot;Please input which option you want, 1, 2, 3, 4, 5, or 6: &quot;)<br>    print(&quot; &quot;)<br><br>    if question == &quot;1&quot;:<br>        name = input(&quot;Enter the name of the person: &quot;).lower()<br>        email = get_valid_email()<br>        number = get_valid_phone()<br>        address = input(&quot;Enter the address of the person: &quot;)<br>        birthday = get_valid_birthday()<br>        location = input(&quot;Enter the location of the person: &quot;)<br><br>        book[name] = {<br>            &quot;number&quot;: number,<br>            &quot;email&quot;: email,<br>            &quot;address&quot;: address,<br>            &quot;birthday&quot;: birthday,<br>            &quot;location&quot;: location<br>        }<br>        save_phonebook()<br>        print(f&quot;The contact for {name.title()} was added successfully&quot;)<br><br>    elif question == &quot;2&quot;:<br>        name = input(&quot;Enter the name of the person whose contact you want to delete: &quot;).lower()<br>        try:<br>            del book[name]<br>            save_phonebook()<br>            print(f&quot;The contact for {name.title()} was deleted successfully&quot;)<br>        except KeyError:<br>            print(&quot;The name doesnt exist&quot;)<br><br>    elif question == &quot;3&quot;:<br>        name = input(&quot;Enter the name of the person whose contact you are looking for: &quot;).lower()<br>        try:<br>            user = book[name]<br>            print(f&quot;The details for the user {name.title()} are as follows: &quot;)<br>            print(f&quot;Phone number: {user[&#39;number&#39;]}&quot;)<br>            print(f&quot;Email: {user[&#39;email&#39;]}&quot;)<br>            print(f&quot;Address: {user[&#39;address&#39;]}&quot;)<br>            print(f&quot;Birthday: {user[&#39;birthday&#39;]}&quot;)<br>            print(f&quot;Location: {user[&#39;location&#39;]}&quot;)<br>        except KeyError:<br>            print(&quot;The name you looked for doesnt exist&quot;)<br><br>    elif question == &quot;4&quot;:<br>        if not book:<br>            print(&quot;The phonebook is currently empty.&quot;)<br>        else:<br>            for item in book:<br>                user = book[item]<br>                print(f&quot;Name: {item.title()}&quot;)<br>                print(f&quot;Phone number: {user[&#39;number&#39;]}&quot;)<br>                print(f&quot;Email: {user[&#39;email&#39;]}&quot;)<br>                print(f&quot;Address: {user[&#39;address&#39;]}&quot;)<br>                print(f&quot;Birthday: {user[&#39;birthday&#39;]}&quot;)<br>                print(f&quot;Location: {user[&#39;location&#39;]}&quot;)<br>                print(&quot;------------------------&quot;)<br><br>    elif question == &quot;5&quot;:<br>        name = input(&quot;Enter the name of the person: &quot;).lower()<br>        if name in book:<br>            email = get_valid_email()<br>            number = get_valid_phone()<br>            address = input(&quot;Enter the address of the person: &quot;)<br>            birthday = get_valid_birthday()<br>            location = input(&quot;Enter the location of the person: &quot;)<br><br>            book[name] = {<br>                &quot;number&quot;: number,<br>                &quot;email&quot;: email,<br>                &quot;address&quot;: address,<br>                &quot;birthday&quot;: birthday,<br>                &quot;location&quot;: location<br>            }<br>            save_phonebook()<br>            print(f&quot;The contact for {name.title()} was edited successfully&quot;)<br>        else:<br>            print(&quot;The user doesnt exist&quot;)<br><br>    elif question == &quot;6&quot;:<br>        print(&quot;Goodbye!&quot;)<br>        break<br><br>    else:<br>        print(&quot;Sorry please choose an option from within 1,2,3,4,5, or 6&quot;)</pre><p><strong>Email</strong>, using a regular expression:</p><pre>def validate_email(email):<br>    pattern = r&quot;^[\w\.-]+@[\w\.-]+\.\w+$&quot;<br>    return re.match(pattern, email) is not None</pre><p>This was my first real use of the re module (regular expressions), something I hadn’t touched yet in this project. Breaking the pattern down:</p><ul><li>[\w\.-]+ means “one or more word characters, dots, or hyphens”, this covers the part before the @.</li><li>@ is just a literal @, required exactly once.</li><li>[\w\.-]+ again for the domain name.</li><li>\. is a literal dot (needs the backslash, since a plain . in regex means “any character”).</li><li>\w+ for the extension (com, org, edu, etc.).</li></ul><p>re.match() checks the string against that pattern from the start, and returns a match object if it fits, or None if it doesn’t. is not None just converts that into a clean True/False.</p><p><strong>Phone number</strong> didn’t need regex at all, just two plain checks:</p><pre>def validate_phone(number):<br>    return number.isdigit() and len(number) == 10</pre><p>.isdigit() confirms every character is a number (so no letters, no dashes, no parentheses), and len(number) == 10 confirms it’s exactly 10 digits. Both conditions have to be true together, which is exactly what and is for.</p><p><strong>Birthday</strong> was the trickiest one, since “valid format” and “valid date” are two different checks:</p><pre>def validate_birthday(birthday):<br>    parts = birthday.split(&quot;/&quot;)<br>    if len(parts) != 3:<br>        return False<br>    month, day, year = parts<br>    if not (month.isdigit() and day.isdigit() and year.isdigit()):<br>        return False<br>    month, day, year = int(month), int(day), int(year)<br>    if not (1 &lt;= month &lt;= 12):<br>        return False<br>    if not (1 &lt;= day &lt;= 31):<br>        return False<br>    if len(str(year)) != 4:<br>        return False<br>    return True</pre><p>First, .split(&quot;/&quot;) breaks the string on the slashes, if that doesn’t produce exactly 3 pieces, it’s already wrong (catches someone typing “10-12-2026” or forgetting a part entirely). Then each piece has to actually be digits before converting to int, since trying to int() something like “abc” would crash with a ValueError rather than failing cleanly. Only after confirming all three pieces are numeric do I check the actual ranges: month between 1 and 12, day between 1 and 31 (I kept this simple rather than checking exact days-per-month, which would mean accounting for February and leap years, something I may revisit later), and year as a 4-digit number.</p><p><strong>Wrapping each one in a retry loop</strong></p><p>Having a validation function is only half the job, the program also needed to actually <em>use</em> it by asking again if the input fails, rather than accepting bad data anyway:</p><pre>def get_valid_email():<br>    while True:<br>        email = input(&quot;Enter the email address of the person: &quot;)<br>        if validate_email(email):<br>            return email<br>        print(&quot;That doesn&#39;t look like a valid email. Try again (e.g. name@example.com)&quot;)</pre><p>This follows the same while True: pattern as the main menu loop, keep asking until the input passes, then return it. Wrapping these as their own functions (get_valid_email, get_valid_phone, get_valid_birthday) meant I could drop a single function call into both the add and edit sections, rather than repeating the validation loop logic in two places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*KoCKQI8RSDGGa8mcEtetwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*YtSI6wDv3McQuBHtz1Qxgw.png" /></figure><p><strong>What I’d still improve</strong></p><p>The phonebook works end to end now: contacts persist across runs, bad input gets caught and re-asked rather than silently accepted, and the exception handling is actually specific instead of a catch-all. But a few things are still sitting on my list for a later pass:</p><p><strong>The add and edit sections are still near-duplicates.</strong> Even with the validation pulled into its own functions, options 1 and 5 still repeat the same five-field block, build the same dictionary shape, and only differ in whether they’re creating a new entry or overwriting an existing one. The natural next step is a single function, something like get_contact_details(), that both branches call and get a dictionary back from, so that structure only exists in one place in the code.</p><p><strong>Birthday validation checks ranges, not real calendar logic.</strong> Right now a day of “31” passes for every month, including February, nothing stops something like 02/31/2026 from being saved. Properly handling this means accounting for actual days-per-month and leap years, which Python’s own datetime module can do for me, by trying to construct a real date and catching the error if it’s invalid, rather than hand-checking ranges myself.</p><p><strong>No way to edit a single field.</strong> Option 5 currently asks for all five fields again, every time, even if I only wanted to update someone’s phone number. A more thoughtful edit flow would show the existing details and let the user pick just the one field to change.</p><p><strong>Everything is still single-user, single-file.</strong> The whole phonebook lives in one JSON file with no concept of multiple phonebooks, backups, or anything beyond the most basic read/write. Fine for a learning project, but worth knowing as a real boundary of what this is.</p><p>None of these are urgent, the program does what it set out to do, but they’re the honest list of what separates “a working beginner project” from something closer to production-shaped code.</p><p><strong>Closing thought</strong></p><p>Coming back to Python after a while away, and picking something this small on purpose, turned out to be a good way to re-expose myself to a bunch of fundamentals at once: dictionaries as lookup tables, file I/O, exception handling, and a first real use of regular expressions, all inside a project simple enough to actually finish in a weekend. It’s not a complicated program, but almost every section ended up teaching me something I’d either forgotten or never fully understood the first time around.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5938fb27f303" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Network/Port Scanner]]></title>
            <link>https://medium.com/@aa2812061/python-network-port-scanner-850cd895861b?source=rss-a4dad81bab85------2</link>
            <guid isPermaLink="false">https://medium.com/p/850cd895861b</guid>
            <category><![CDATA[network-scanner]]></category>
            <category><![CDATA[port-scanning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[threading]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <dc:creator><![CDATA[Luffytaroouu]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 19:35:38 GMT</pubDate>
            <atom:updated>2026-10-03T00:58:01.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ur0BgsquH0WoA6Mw" /></figure><p>So, I woke up and had a thought about using Python to build a network scanner, but I haven’t used Python for a project in a while, and this would be two birds with one arrow: I get to revise Python and also learn more about actually building a scanner. So, deciding to build a scanner, I wondered what the things and questions I would have to solve would be before I could actually build the scanner itself. I went into Claude, gave it my whole detailed plan for the project, and asked it the same question, and it gave me questions that would teach me the whole step-by-step process.</p><p>My first question was what module would be used to build this. I have had some experience with ‘scapy’ for school projects, so that was my first thought, but as per the questions that Claude gave me, it seemed like checking out a built-in Python module, “Socket,” was the correct option.</p><p>I used Python’s official documentation and the following links to learn more about the Socket module:</p><p><a href="https://docs.python.org/3/library/socket.html">https://docs.python.org/3/library/socket.html</a></p><p><a href="https://www.pythonsheets.com/notes/network/python-socket.html#get-network-interfaces">https://www.pythonsheets.com/notes/network/python-socket.html#get-network-interfaces</a></p><p><a href="https://www.w3schools.com/python/ref_module_socket.asp">https://www.w3schools.com/python/ref_module_socket.asp</a></p><p>After going through these documents, I learned a bit of the background about the module. Now let’s check the questions given by Claude and get to solving them one by one.</p><p><strong>Level 1 — Socket basics (just connecting)</strong></p><ol><li><strong>What’s my IP?</strong> — Use the socket module to get your own machine’s hostname and local IP address and print them.</li></ol><p>So, checking what my hostname is was very straightforward; as in the document I referenced above, it gave me the socket.gethostname() method.</p><pre>import socket<br><br>name = socket.gethostname()<br>print (name)</pre><p>This was plenty to get the hostname of my device; getting the IP address was a little tricky. I tried to get it by looking up my hostname, basically using socket.gethostbyname(socket.gethostname()). Here, we know that socket.gethostname() gets you the hostname for my device, as we already know from above, and socket.gethostbyname() gets me the IP address for that host by reverse DNS lookup. Now, the issue was that when I tried this, I got the loopback IP address, and while that wasn’t a failure, it definitely wasn’t the answer we were looking for. So, I started researching again and found this Stack Overflow thread: <a href="https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib">https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib</a></p><p>Here in the comments, I found that my previous attempt, where I passed my hostname into the reverse DNS lookup method, likely failed because I was running Linux on Windows Subsystem for Linux (WSL), and it couldn’t find my local IP address. In the same Stack Overflow thread, I also found a possible solution for my problem. It gave me an idea to open a socket connection to a random IP or domain, and from there we could check which of my sockets (interfaces) was used for that connection and what the IP address for that socket was.</p><pre>import socket<br><br>name = socket.gethostname()<br>print (name)<br>s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)<br>s.connect((&quot;8.8.8.8&quot;, 80))<br>ipadd = s.getsockname()[0]<br>print (ipadd)</pre><p>Here, socket.AF_INET defines that I am going to use an IPv4 address, and socket.DGRAM defines that I am going to make a connection to a UDP port. Now, as we know, UDP doesn’t have a handshake process; it will just send data to the defined IP address on the mentioned port and be done with it.</p><p>For the next line in the code, s.connect((“8.8.8.8”, 80)), I defined that I am connecting to Google’s DNS IP on port 80. I had to use two brackets here, as s.connect only takes one argument, but I have to pass the IP address and also the port number, which required me to use a tuple instead. So, the first bracket is for the method itself, and the second bracket is for the tuple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*0rRYDExZq4YHgXw08tJlPw.png" /></figure><p>Similarly, I used s.getsockname() to get the IP address of the interface that was used to make this connection, but realized that this also results in printing the port number my device used for this connection. So, just like when we only print one particular item from the list, I chose to only print the first item, which is the IP address; hence, I used [0]. It’s like print (list[0]), where only the first item from the list would be printed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*TcOj75_LQgTsTgGM6g7XSg.png" /></figure><p><strong>2. Single connection test</strong> — Ask the user for a hostname (like “google.com”) and a port number (like 80). Try to open a socket connection to it and print whether it succeeded or failed.</p><p>I felt like this was simple since we had already made a connection in the previous question, so I just copied the old code and went on adding a few lines to it.</p><pre>import socket<br><br>hostname = input(&quot;Enter a hostname: &quot;)<br>port = int(input (&quot;Enter a port: &quot;))<br>s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)<br>s.settimeout(3.0)<br>s.connect((hostname, port))<br>print (&quot;success&quot;)</pre><p>Here, all that is added from the previous question was the timeout part: s.settimeout(3.0) would wait for three seconds to make a connection and then disconnect. After actually running this, I realized all the connections were positive, and maybe there was an error in my code. I also realized that I am using UDP, which is connectionless, meaning it sends the data and then doesn’t really care if it reached the destination or not. So, I switched to using TCP instead.</p><pre>import socket<br><br>hostname = input(&quot;Enter a hostname: &quot;)<br>port = int(input (&quot;Enter a port: &quot;))<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.settimeout(3.0)<br>s.connect((hostname, port))<br>print (&quot;success&quot;)</pre><p>This code legitimately checks whether the connection was made or not. If the connection was successful, it would print success, but if it failed, it would give me an error and stop the code. An example is below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*GVOMylYxgGwOG2iZQkeofA.png" /></figure><p>Here, you can see that when I set a port too high, it gave me an error saying that the port has to be between 0–65535. Now I didn’t want these errors and wanted them handled properly, so I checked the possible errors in Python’s official documentation and updated the code for error handling accordingly</p><p><a href="https://docs.python.org/3/library/socket.html#exceptions">socket - Low-level networking interface</a></p><pre>import socket<br><br>hostname = input(&quot;Enter a hostname: &quot;)<br>port = int(input (&quot;Enter a port: &quot;))<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.settimeout(3.0)<br><br>try:<br>    s.connect((hostname, port))<br>    print (&quot;The connection was successful&quot;)<br>except OverflowError:<br>    print(&quot;Port must be between 0 and 65535&quot;)<br>except socket.gaierror:<br>    print(&quot;Could not resolve hostname&quot;)<br>except ConnectionRefusedError:<br>    print(&quot;Connection actively refused (port closed)&quot;)<br>except socket.timeout:<br>    print(&quot;No response — connection timed out (port filtered or host unreachable)&quot;)<br>    s.close()</pre><p>Now this shows when the connection was successful, and if it fails, it prints why it failed instead of giving us an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*OVeAdCPqvIWlvx77k28Cjw.png" /></figure><p>I tested it again, and while testing, I saw that there were some errors that might still go through that I didn’t anticipate, so I added another line. The screenshot above shows the error we got before and after the fix.</p><pre>import socket<br><br>hostname = input(&quot;Enter a hostname: &quot;)<br>port = int(input (&quot;Enter a port: &quot;))<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.settimeout(3.0)<br><br>try:<br>    s.connect((hostname, port))<br>    print (&quot;The connection was sucessful&quot;)<br>except OverflowError:<br>    print(&quot;Port must be between 0 and 65535&quot;)<br>except socket.gaierror:<br>    print(&quot;Could not resolve hostname&quot;)<br>except ConnectionRefusedError:<br>    print(&quot;Connection actively refused (port closed)&quot;)<br>except socket.timeout:<br>    print(&quot;No response — connection timed out (port filtered or host unreachable)&quot;)<br>except socket.error as e:<br>    print (&quot;The error was &quot;, e )<br>finally:<br>    s.close()</pre><p><strong>3. Resolve a domain to an IP</strong> — Ask the user for a domain name (like “example.com”) and use socket to resolve and print its IP address.</p><p>This question turned out to be straightforward because of the mistake I had already made in the first question; I just needed to use socket.gethostbyname() and pass the name of the host there, with error handling.</p><blockquote>Here I realized that this might actually be teaching me, as I could use what I learnt previously here, and it was helping me grow lol.</blockquote><pre>import socket<br>hostname = input(&quot;Enter a hostname: &quot;)<br><br>try:<br>    ipadd = socket.gethostbyname(hostname)<br>    print (ipadd)<br>except (socket.gaierror, OverflowError, ConnectionRefusedError) as e:<br>    print (&quot;The lookup failed because &quot;, e)</pre><p>All I did was what we had already done in the first and second question: I let the user input the hostname and did a reverse DNS lookup to get the IP address for that hostname, and also used try/except for error handling in case users passed something random in the hostname section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*bm3ZXs5vNvPLz440-t35BQ.png" /></figure><p><strong>4. Grab a banner</strong> — Connect to a known open port (try port 80 on a website) and print whatever data the server sends back immediately after connecting (this is called a “banner” — many services announce themselves).</p><p>For this question, I had to research again, and I went through these three links</p><p><a href="https://stackoverflow.com/questions/17024212/grab-banner-of-different-ports-with-python">https://stackoverflow.com/questions/17024212/grab-banner-of-different-ports-with-python</a></p><p><a href="https://medium.com/@rajesh.p3807/building-a-simple-python-banner-grabbing-script-a-step-by-step-guide-6538f2d26804">https://medium.com/@rajesh.p3807/building-a-simple-python-banner-grabbing-script-a-step-by-step-guide-6538f2d26804</a></p><p><a href="https://ballingt.com/banner-grabbing-with-python/">https://ballingt.com/banner-grabbing-with-python/</a></p><p>I only opened another method that would check anything that is received from the connection and print it, and it also has error handling, as shown below. I did limit the receiving bytes to 1024, as I believed that for a test run this would be enough.</p><pre>import socket<br><br>hostname = input(&quot;Enter a hostname: &quot;)<br>port = int(input (&quot;Enter a port: &quot;))<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.settimeout(3.0)<br>try:<br>    s.connect((hostname, port))<br>    banner = s.recv(1024)<br>    print (banner)<br>except socket.error as e:<br>    print(&quot;The error is &quot;, e)<br>s.close()</pre><p>Since I was still testing and wanted relevant answers so I could update my code accordingly, I ran a Metasploitable server on my device using VirtualBox and ran the program to banner grab against my Metasploitable. During the process I checked different ports such as 21,22,23,25 and 80. It worked fine for most of these, but while trying to connect to port 80, it showed a timeout error, and when connecting to telnet, it showed me raw bytes, as evident below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*gFyfSgUuRS8Qm7lK9bmUfg.png" /></figure><p>So, I researched a bit more, and apparently, unlike most ports, telnet doesn’t respond in plain text, so when banner-grabbing telnet, such a response is normal. Similarly, for HTTP, we need to send/request data to be able to receive anything, so let’s make some changes in the code to ensure that this works better now.</p><pre>import socket<br><br>hostname = input(&quot;Enter a hostname: &quot;)<br>port = int(input (&quot;Enter a port: &quot;))<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.settimeout(3.0)<br>try:<br>    s.connect((hostname, port))<br>    s.send(b&#39;GET /\n\n&#39;)<br>    banner = s.recv(1024)<br>    print (banner)<br>except socket.error as e:<br>    print(&quot;The error is &quot;, e)<br>s.close()</pre><p>I added sending a GET request in the code and tried banner grabbing on port 80 again, and it worked as intended for the most part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*wSlzKkOsAPsEGrFjFYEdbg.png" /></figure><p>Since we were still getting issues when connecting to HTTP, I changed the script a bit more and realized that there are some important things to add when requesting a banner through port 80: one is the method, which we are using GET method; next is the version of HTTP we want to use. So, I changed the script to add an HTTP version. We also needed the hostname of the website, so I added the</p><pre>import socket<br><br>hostname = input(&quot;Enter a hostname: &quot;)<br>port = int(input (&quot;Enter a port: &quot;))<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.settimeout(3.0)<br>try:<br>    s.connect((hostname, port))<br>    request = f&quot;GET / HTTP/1.1 \r\n Host: {hostname}\r\n\r\n&quot;<br>    s.send(request.encode())<br>    banner = s.recv(1024)<br>    print (banner)<br>except socket.error as e:<br>    print(&quot;The error is &quot;, e)<br>s.close()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*BUi-Hq7lDcHgDlzXKcllEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Ekshpc1ridffx4tXgHDueQ.png" /></figure><p>Here you can see what it looks like and that I am still getting an error. So, to figure out what mistake I am making, I checked by sending an actual request to an HTTP website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*oTAkuSyb_jsQYIfLjKtOng.png" /></figure><p>Here you can see that there is more information being sent by a browser when accessing a website, so let’s copy something similar to that in ours as well. Before doing so, I checked with Claude, and it basically told me that extra spaces were where the problem was and to remove extra spaces, as Python reads the extra spaces also as actual characters, which can cause errors.</p><pre>import socket<br><br>hostname = input(&quot;Enter a hostname: &quot;)<br>port = int(input (&quot;Enter a port: &quot;))<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.settimeout(3.0)<br>try:<br>    s.connect((hostname, port))<br>    request = f&quot;GET / HTTP/1.1\r\nHost: {hostname}\r\n\r\n&quot;<br>    s.send(request.encode())<br>    banner = s.recv(1024)<br>    print (repr(banner))<br>except socket.error as e:<br>    print(&quot;The error is &quot;, e)<br>s.close()</pre><p>Now let’s compare the result before and after below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Qcd_HCEXqa97lDgU-et1jA.png" /></figure><p>There you can see my request, and inside the red box in the black highlight, the response we saw in the reply within python, we restricted the response to 1024 bits, so we only saw a limited part of the reply below. In Wireshark, you can see the whole thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*nf4_UyoICxY7FBgvqVsH4Q.png" /></figure><p>FYI, I forgot to mention this above, but in the response, I added print(repr(banner)). The repr here stands for “representation”, so that the answer is printed in its raw form. As in, \r\n would also be seen.</p><p><strong>Level 2 — Checking multiple things (loops + sockets together)</strong></p><p><strong>5. Port range checker</strong> — Ask the user for a hostname and a <em>range</em> of ports (e.g., 1–100). Loop through each port and print whether it’s open or closed.</p><pre>6. import socket<br>7. <br>8. hostname = input(&quot;Enter a hostname: &quot;)<br>9. start = int(input (&quot;Enter the starting port: &quot;))<br>10. end = int(input (&quot;Enter the ending port: &quot;))<br>11. <br>12. for x in range(start, end):<br>13.     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>14.     s.settimeout(1.0)<br>15.     result = s.connect_ex((hostname, x))<br>16.     if result == 0:<br>17.         print (&quot;The port&quot;,x, &quot;is open&quot;)<br>18.         s.close()<br>19.     else:<br>20.         print (&quot;The port&quot;, x, &quot;is closed&quot;)<br>21.         s.close()</pre><p>This took me a while, but in the end, it was pretty straightforward. Above, you can see the code that works; it will print whether the port is opened or closed properly.</p><p>Initially, the mistake I made was that I put the s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) part and the s.settimeout(1.0) part outside the loop. Basically, what that did was that only the first port was checked, and all the others errored out because apparently a socket created can only be used once and then it closes, so for each new connection we need a new socket to open; hence why I had to put the socket declaration and timeout inside the loop.</p><p>Here are the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*GCcwgCIqATudlpYEDgAOlA.png" /></figure><p><strong>6.</strong> <strong>Timeout handling</strong> — Take your port checker from #5 and add a timeout, so a single slow/unresponsive port doesn’t freeze the whole scan for ages. Print how long the full scan took.</p><pre>7. import socket<br>8. import datetime<br>9. hostname = input(&quot;Enter a hostname: &quot;)<br>10. <br>11. initial_time = datetime.datetime.now()<br>12. <br>13. for x in range(0, 65535):<br>14.     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>15.     s.settimeout(0.2)<br>16.     result = s.connect_ex((hostname, x))<br>17.     if result == 0:<br>18.         print (&quot;The port&quot;,x, &quot;is open&quot;)<br>19.         s.close()<br>20.     else:<br>21.         pass<br>22.         s.close()<br>23. final_time = datetime.datetime.now()<br>24. scan_time = final_time - initial_time<br>25. print(&quot;The total time taken was: &quot;, scan_time)</pre><p>This one was just an addition to the last question; I removed the printing “that the port is closed” and put pass in there so the loop keeps going and we only get the open ports. Also, to check how long it took, I imported the datetime module and checked the time before the loop started and after it was done and subtracted them from each other to get how long it actually ran. While importing, we could have used “from datetime import datetime” instead of just “import datetime”; that way, we wouldn’t have to write datetime twice when calling it later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*tNwFWyHWra8BY9pWt7wO_g.png" /></figure><p><strong>7.</strong> <strong>Common ports list</strong> — Instead of scanning every port in a range, build a Python list/dict of well-known ports (21-FTP, 22-SSH, 80-HTTP, 443-HTTPS, 445-SMB, 3389-RDP) and scan just those, printing the service name next to each result.</p><p>This again was similar to the last question; we only needed to add a dictionary that defined what service was running on which port and run a for loop that would go through each value in the dictionary and then print it with the value on the key as shown below.</p><pre>import socket<br>import datetime<br>hostname = input(&quot;Enter a hostname: &quot;)<br>ports_to_scan = {&quot;FTP&quot;:&quot;21&quot;, &quot;SSH&quot;:&quot;22&quot;, &quot;SMTP&quot;:&quot;25&quot;, &quot;HTTP&quot;:&quot;80&quot;, &quot;HTTPS&quot;:&quot;443&quot;, &quot;SMB&quot;:&quot;445&quot;, &quot;RDP&quot;:&quot;3389&quot;}<br>initial_time = datetime.datetime.now()<br><br>for value in ports_to_scan.values():<br>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    s.settimeout(0.2)<br>    result = s.connect_ex((hostname, int(value)))<br>    if result == 0:<br>        print (&quot;The port&quot;,value, &quot;is open&quot;)<br>        s.close()<br>    else:<br>        pass<br>        s.close()<br>final_time = datetime.datetime.now()<br>scan_time = final_time - initial_time<br>print(&quot;The total time taken was: &quot;, scan_time)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*dRSDds-ue3SwNSV8xML8-g.png" /></figure><p>I did this first and realized that I only got the value, not the key. So, since while printing I also need the key lets change the code a little bit.</p><pre>import socket<br>import datetime<br>hostname = input(&quot;Enter a hostname: &quot;)<br>ports_to_scan = {&quot;FTP&quot;:&quot;21&quot;, &quot;SSH&quot;:&quot;22&quot;, &quot;SMTP&quot;:&quot;25&quot;, &quot;HTTP&quot;:&quot;80&quot;, &quot;HTTPS&quot;:&quot;443&quot;, &quot;SMB&quot;:&quot;445&quot;, &quot;RDP&quot;:&quot;3389&quot;}<br>initial_time = datetime.datetime.now()<br><br>for key,value in ports_to_scan.items():<br>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    s.settimeout(0.2)<br>    result = s.connect_ex((hostname, int(value)))<br>    if result == 0:<br>        print (&quot;The port&quot;,value, &quot;is open. It runs following service: &quot;, key)<br>        s.close()<br>    else:<br>        pass<br>        s.close()<br>final_time = datetime.datetime.now()<br>scan_time = final_time - initial_time<br>print(&quot;The total time taken was: &quot;, scan_time)</pre><p>That prints the port and what is running on the port as well, just like we initially wanted</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*glCSjZqS8VAlpw0ri-c37w.png" /></figure><p><strong>Level 3 — Command-line arguments (using sys)</strong></p><p><strong>8. Take input from the command line instead of input()</strong> — Use sys.argv to let the user run your script like python scanner.py google.com 80 instead of being prompted interactively. Print out what arguments were received.</p><p>This might have been one of the most confusing exercises that I did till now. I had no idea how sys.argv worked, but it turns out it was similar to how I use PowerShell and basically just passing in arguments when we are running the file.</p><p>Here is the script I used for the exercise that worked. (Note: sys.argv[0] is the name of the file, and from sys.argv[1], we can put in which parameters we want and where we want them accordingly. Similarly, the arguments we put in using sys.argv are strings, but as we know port numbers are integers, so make sure to convert that to int.</p><pre>import sys<br>import socket<br>import datetime<br><br>hostname = sys.argv[1]<br>port = sys.argv[2]<br>initial_time = datetime.datetime.now()<br>print(&quot;The host that the user wants scanned is &quot;, sys.argv[1])<br>print(&quot;The port that the user wants scanned is &quot;, sys.argv[2])<br><br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.settimeout(3.0)<br>try:<br>    s.connect((hostname, int(port)))<br>    request = f&quot;GET / HTTP/1.1\r\nHost: {hostname}\r\n\r\n&quot;<br>    s.send(request.encode())<br>    banner = s.recv(2056)<br>    print (repr(banner))<br>except socket.error as e:<br>    print(&quot;The error is &quot;, e)<br>s.close()</pre><p>Here is my result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Kj4HSmgWP4t9lnGR-gmeaQ.png" /></figure><p><strong>9. Argument validation</strong> — Extend #8 so if the user forgets to provide a hostname or port, your script prints a helpful usage message (“Usage: python scanner.py &lt;host&gt; &lt;port&gt;”) and exits cleanly instead of crashing.</p><pre>10. import sys<br>11. import socket<br>12. import datetime<br>13. if len(sys.argv) == 3:<br>14.     hostname = sys.argv[1]<br>15.     port = sys.argv[2]<br>16.     initial_time = datetime.datetime.now()<br>17.     print(&quot;The host that the user wants scanned is &quot;, sys.argv[1])<br>18.     print(&quot;The port that the user wants scanned is &quot;, sys.argv[2])<br>19. <br>20.     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>21.     s.settimeout(3.0)<br>22.     try:<br>23.         s.connect((hostname, int(port)))<br>24.         request = f&quot;GET / HTTP/1.1\r\nHost: {hostname}\r\n\r\n&quot;<br>25.         s.send(request.encode())<br>26.         banner = s.recv(2056)<br>27.         print (repr(banner))<br>28.     except socket.error as e:<br>29.         print(&quot;The error is &quot;, e)<br>30.     s.close()<br>31. elif len(sys.argv) &lt; 3:<br>32.     print (&quot;You passed too few arguments, put in the ip address and portnumber you want scanned&quot;)<br>33. else:<br>34.     print (&quot;You passed too many arguments, put in the ip address and portnumber you want scanned&quot;)</pre><p>All I had to do for this task was put a loop to check if the number of arguments we were expecting was present or not, so I counted the sys.argv list using len() and checked if it had 3 items; if it did, then the code would run; else it would print a message accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*8n4hvg6bAd0yx8MAwC2K3Q.png" /></figure><p><strong>10.</strong> <strong>Multiple ports via command line</strong> — Let the user pass a comma-separated list of ports (python scanner.py google.com 22,80,443) and scan all of them.</p><p>For this exercise, we need to take multiple ports in, which is not hard. We just add commas in the command line and put in more ports, so what changes? We know that when we insert anything from the command line, it goes in as a string. So, we have to break that string into something like a list so we can make it work, and then we could use a for loop as we did before and scan each port. For this purpose, we use the “.split()” method. This method is used to break down a string into multiple sections, and we can choose where to split the string. Since we determined that we will be inputting multiple strings using commas, let’s do the same here. So, for sys.argv[2], where we get the port, we will use .split(“,”) to split them by commas. Sys.argv[2].split(“,”).</p><p>The following is the code.</p><pre>import sys<br>import socket<br>import datetime<br>if len(sys.argv) == 3:<br>    hostname = sys.argv[1]<br>    port = sys.argv[2].split(&quot;,&quot;)<br>    initial_time = datetime.datetime.now()<br>    print(&quot;The host that the user wants scanned is &quot;, sys.argv[1])<br>    print(&quot;The port that the user wants scanned is &quot;, sys.argv[2])<br><br>    for x in port:<br>    <br>        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>        s.settimeout(3.0)<br>        try:<br>            s.connect((hostname, int(x)))<br>            request = f&quot;GET / HTTP/1.1\r\nHost: {hostname}\r\n\r\n&quot;<br>            s.send(request.encode())<br>            banner = s.recv(2056)<br>            print (repr(banner))<br>        except socket.error as e:<br>            print(&quot;The error is: &quot;, e)<br>        s.close()<br>elif len(sys.argv) &lt; 3:<br>    print (&quot;You passed too few arguments, put in the ip address and portnumber you want scanned&quot;)<br>else:<br>    print (&quot;You passed too many arguments, put in the ip address and portnumber you want scanned&quot;)</pre><p>Result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*9GZCkwQa0Sl1jgEGA6xlaQ.png" /></figure><p><strong>Level 4 — Speed and structure (this is where it starts feeling “real”)</strong></p><p><strong>11. Threading for speed</strong> — Your Level 2 scanner checks ports one at a time, which is slow for large ranges. Learn threading (or concurrent.futures) to check multiple ports <em>simultaneously</em> and compare the time difference against your sequential version from #6.</p><p>Ughh, this was a tough one. I had to research threading and concurrent.futures, and honestly went with concurrent.futures just because I found some documentation and it seemed more interesting to learn. These were some of the links I took reference from</p><p><a href="https://alexwlchan.net/2019/adventures-with-concurrent-futures/">https://alexwlchan.net/2019/adventures-with-concurrent-futures/</a></p><p><a href="https://www.packetswitch.co.uk/what-is-concurrent-futures-and-how-can-it-boost-your-python-performance/">https://www.packetswitch.co.uk/what-is-concurrent-futures-and-how-can-it-boost-your-python-performance/</a></p><p><a href="https://docs.python.org/3/library/concurrent.futures.html">https://docs.python.org/3/library/concurrent.futures.html</a><br> <a href="https://medium.com/@smrati.katiyar/introduction-to-concurrent-futures-in-python-009fe1d4592c">https://medium.com/@smrati.katiyar/introduction-to-concurrent-futures-in-python-009fe1d4592c</a></p><p><a href="https://www.pythonsheets.com/notes/concurrency/python-futures.html">https://www.pythonsheets.com/notes/concurrency/python-futures.html</a></p><p>I made a function out of the scanning part so that we could call it multiple times (cause again the whole purpose of this is to run multiple scans at the same time; the previous loops only did one at a time). The following is the code:</p><pre>import sys<br>import socket<br>import datetime<br>import concurrent.futures<br><br>def scan_port(hostname, port):<br>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    s.settimeout(3.0)<br>    try:<br>        s.connect((hostname, port))<br>        request = f&quot;GET / HTTP/1.1\r\nHost: {hostname}\r\n\r\n&quot;<br>        s.send(request.encode())<br>        banner = s.recv(2056)<br>        print(f&quot;Port {port}:&quot;, repr(banner))<br>    except socket.error as e:<br>        print(f&quot;Port {port}: error -&quot;, e)<br>    finally:<br>        s.close()<br><br>if len(sys.argv) == 3:<br>    hostname = sys.argv[1]<br>    ports = range(0,65535)<br><br>    print(&quot;The host that the user wants scanned is &quot;, hostname)<br>    print(&quot;The ports that the user wants scanned are &quot;, ports)<br><br>    initial_time = datetime.datetime.now()<br><br>    with concurrent.futures.ThreadPoolExecutor() as executor:<br>        for port in ports:<br>            executor.submit(scan_port, hostname, port)<br><br>    final_time = datetime.datetime.now()<br>    print(&quot;The total time taken was: &quot;, final_time - initial_time)<br><br>elif len(sys.argv) &lt; 3:<br>    print(&quot;You passed too few arguments, put in the ip address and port number you want scanned&quot;)<br>else:<br>    print(&quot;You passed too many arguments, put in the ip address and port number you want scanned&quot;)</pre><p>Here, everything else is the same; it takes a hostname from the command line and scans the port from 0–65535, so basically all ports. I also put the time-checking format back in for this, as I also wanted to compare it with the previous exercise where we scanned all ports and wanted to check the difference in time. Initially, when I ran the script, I realized that since I was also printing the errors, there were a lotta errors, so I removed the error-printing part and used pass there so only the connected ports would be printed.</p><p>You can see underneath how it looked initially. We can see that the time taken has significantly reduced; previously, when we ran the program sequentially, it took around 4 minutes; now it takes around one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*4QMru-XncKGPRkwohULLfQ.png" /></figure><p>I changed the program as follows</p><pre>import sys<br>import socket<br>import datetime<br>import concurrent.futures<br><br>def scan_port(hostname, port):<br>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    s.settimeout(3.0)<br>    try:<br>        s.connect((hostname, port))<br>        request = f&quot;GET / HTTP/1.1\r\nHost: {hostname}\r\n\r\n&quot;<br>        s.send(request.encode())<br>        banner = s.recv(2056)<br>        print(f&quot;Port {port}:&quot;, repr(banner))<br>    except socket.error as e:<br>        pass<br>    finally:<br>        s.close()<br><br>if len(sys.argv) == 3:<br>    hostname = sys.argv[1]<br>    ports = range(0,65535)<br><br>    print(&quot;The host that the user wants scanned is &quot;, hostname)<br>    print(&quot;The ports that the user wants scanned are &quot;, ports)<br><br>    initial_time = datetime.datetime.now()<br><br>    with concurrent.futures.ThreadPoolExecutor() as executor:<br>        for port in ports:<br>            executor.submit(scan_port, hostname, port)<br><br>    final_time = datetime.datetime.now()<br>    print(&quot;The total time taken was: &quot;, final_time - initial_time)<br><br>elif len(sys.argv) &lt; 3:<br>    print(&quot;You passed too few arguments, put in the ip address and port number you want scanned&quot;)<br>else:<br>    print(&quot;You passed too many arguments, put in the ip address and port number you want scanned&quot;)</pre><p>Also realized that since we weren’t using multiple ports given by the user instead of scanning all possible ports, I removed the if statement cause len(sys.argv) wouldn’t be equal to 3 anymore. I also realized that since, in one of the tasks, we removed the connect_ex method and tried to banner grab for HTTP, a lot of ports that aren’t chatty stopped responding, so basically when I used this program to scan, this is the result I got.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*6Maj64U6q2xD5EkK8Hlwaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*WuENaiwr5NZTsGe3mOUoDQ.png" /></figure><p>Now, based on the results, I knew that it wasn’t showing all the open ports, as I am running the scan against my Metasploitable. Then, when I looked into it, I realized that because I was only sending the HTTP-encoded request, most other protocols saw that and ignored it and without the .connect_ex, we couldn’t confirm if the port was open or not; we assumed the port was closed, so I went back and changed the script to the following</p><pre>import sys<br>import datetime<br>import concurrent.futures<br>import socket<br><br>def scanningPorts(hostname, port):<br>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    s.settimeout(5.0)<br>    result = s.connect_ex((hostname, port))<br><br>    if result == 0:<br>        print(f&quot;The port numbered: {port} is open&quot;)<br>        if port == 80:<br>            try:<br>                request = f&quot;GET / HTTP/1.1\r\nHost: {hostname}\r\n\r\n&quot;<br>                s.send(request.encode())<br>                banner = s.recv(2056)<br>                print(f&quot;Port {port} banner:&quot;, repr(banner))<br>            except socket.error as e:<br>                print(f&quot;Port {port}: connected, but banner grab failed -&quot;, e)<br><br>    s.close()<br><br>hostname = sys.argv[1]<br>ports = range(0, 65535)<br><br>print(&quot;The host that the user wants scanned is &quot;, hostname)<br>print(&quot;The ports that the user wants scanned are &quot;, ports)<br><br>initial_time = datetime.datetime.now()<br><br>with concurrent.futures.ThreadPoolExecutor() as executor:<br>    for port in ports:<br>        executor.submit(scanningPorts, hostname, port)<br><br>final_time = datetime.datetime.now()<br>print(&quot;The total time taken was: &quot;, final_time - initial_time)</pre><p>Now, with an exception made for HTTP, the scan worked properly. Here are the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*FBej_R0Avi3F3vqZyvlM5A.png" /></figure><p><strong>12. Organize into functions/classes</strong> — Refactor everything so far into clean, reusable functions (scan_port(host, port), scan_range(host, start, end)) rather than one long script</p><p>For this, I thought about it and wanted to combine what we have done before. Until now, I have been changing the script in case I want to check a range of ports, a particular port, or a list of ports, but now I want to combine these and use conditional statements. So basically, when we input a single port from the command line, only that port gets scanned. If we want a list of ports, we can comma-separate and input a list of ports, and just like before, it will get split by commas, and each of those ports gets scanned. Furthermore, for a range of ports, I used the same logic; I split it with a hyphen, then put it in the range(start,end) function.</p><p>Here is the code for it</p><pre>import sys<br>import datetime<br>import concurrent.futures<br>import socket<br><br>def scanningPorts(hostname, port):<br>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    s.settimeout(3.0)<br>    result = s.connect_ex((hostname, port))<br><br>    if result == 0:<br>        print(f&quot;The port numbered: {port} is open&quot;)<br>        if port == 80:<br>            try:<br>                request = f&quot;GET / HTTP/1.1\r\nHost: {hostname}\r\n\r\n&quot;<br>                s.send(request.encode())<br>                banner = s.recv(2056)<br>                print(f&quot;Port {port} banner:&quot;, repr(banner))<br>            except socket.error as e:<br>                print(f&quot;Port {port}: connected, but banner grab failed -&quot;, e)<br>    s.close()<br><br>if len(sys.argv) != 3:<br>    print(&quot;Usage: python scanner.py &lt;host&gt; &lt;port | port1,port2,... | start-end&gt;&quot;)<br>    sys.exit()<br><br>hostname = sys.argv[1]<br>port_arg = sys.argv[2]<br><br>if &quot;,&quot; in port_arg:<br>    ports = [int(p) for p in port_arg.split(&quot;,&quot;)]<br>elif &quot;-&quot; in port_arg:<br>    start, end = port_arg.split(&quot;-&quot;)<br>    ports = range(int(start), int(end) + 1)<br>else:<br>    ports = [int(port_arg)]<br><br>print(&quot;The host that the user wants scanned is &quot;, hostname)<br>print(&quot;The ports that the user wants scanned are &quot;, list(ports))<br><br>initial_time = datetime.datetime.now()<br><br>with concurrent.futures.ThreadPoolExecutor() as executor:<br>    for port in ports:<br>        executor.submit(scanningPorts, hostname, port)<br><br>final_time = datetime.datetime.now()<br>print(&quot;The total time taken was: &quot;, final_time - initial_time)</pre><p>Here are the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*d4z9q-vBTwUGgijiK_o9uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*cuNsTwZqRu-Htirhvdop6w.png" /></figure><p>Honestly, I think it is working beautifully at this point.</p><p><strong>Level 5 — Real network scanning concepts</strong></p><p>13. <strong>Host discovery (ping sweep)</strong> — Before scanning ports on a single host, learn to check which hosts on a subnet are even <em>alive</em> — this usually means either shelling out to the system ping command via subprocess, or building a simple ICMP check.</p><p>Till now, we were running the scan against a particular IP address, or hostname; now let’s run the scan against a list/range of ip addresses</p><pre>import sys<br>import subprocess<br>import socket<br>import datetime<br>import concurrent.futures<br>import ipaddress<br><br>def parse_range(spec, convert):<br>    &quot;&quot;&quot;Parse a &#39;single&#39;, &#39;a,b,c&#39;, or &#39;start-end&#39; spec into a list, using `convert` to turn each piece into its real type.&quot;&quot;&quot;<br>    if &quot;,&quot; in spec:<br>        return [convert(p) for p in spec.split(&quot;,&quot;)]<br>    elif &quot;-&quot; in spec:<br>        start_str, end_str = spec.split(&quot;-&quot;)<br>        start = convert(start_str)<br>        end = convert(end_str)<br>        return [convert(i) for i in range(int(start), int(end) + 1)]<br>    else:<br>        return [convert(spec)]<br><br>def ping_host(ip):<br>    result = subprocess.run(<br>        [&quot;ping&quot;, &quot;-c&quot;, &quot;1&quot;, &quot;-W&quot;, &quot;1&quot;, str(ip)],<br>        stdout=subprocess.DEVNULL,<br>        stderr=subprocess.DEVNULL<br>    )<br>    return result.returncode == 0<br><br>def scan_port(hostname, port):<br>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    s.settimeout(1.0)<br>    result = s.connect_ex((hostname, port))<br>    s.close()<br>    return result == 0<br><br>if len(sys.argv) != 3:<br>    print(&quot;Usage: python sweep.py &lt;ip | ip1,ip2,... | start_ip-end_ip&gt; &lt;port | port1,port2,... | start-end&gt;&quot;)<br>    sys.exit()<br><br>ip_arg = sys.argv[1]<br>port_arg = sys.argv[2]<br><br>targets = parse_range(ip_arg, ipaddress.ip_address)<br>ports = parse_range(port_arg, int)<br><br>print(f&quot;Scanning {len(targets)} host(s) across {len(ports)} port(s)...&quot;)<br><br>initial_time = datetime.datetime.now()<br><br>with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:<br>    ping_futures = {executor.submit(ping_host, ip): ip for ip in targets}<br>    alive_hosts = []<br>    for future in concurrent.futures.as_completed(ping_futures):<br>        ip = ping_futures[future]<br>        if future.result():<br>            alive_hosts.append(ip)<br><br>print(f&quot;\n{len(alive_hosts)} of {len(targets)} hosts are alive:&quot;)<br>for ip in sorted(alive_hosts, key=lambda ip: int(ip)):<br>    print(&quot; &quot;, ip)<br><br>with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:<br>    port_futures = {}<br>    for ip in alive_hosts:<br>        for port in ports:<br>            future = executor.submit(scan_port, str(ip), port)<br>            port_futures[future] = (ip, port)<br><br>    print(&quot;\nOpen ports:&quot;)<br>    for future in concurrent.futures.as_completed(port_futures):<br>        ip, port = port_futures[future]<br>        if future.result():<br>            print(f&quot;  {ip}:{port} is open&quot;)<br><br>final_time = datetime.datetime.now()<br>print(&quot;\nTotal time taken:&quot;, final_time - initial_time)</pre><p>Until now I had two almost identical pieces of code doing the same kind of parsing — one for ports (splitting on commas or a dash) back in exercise #12, and I needed the same logic for IPs now too. Instead of just copy-pasting the same if/elif/else block twice with minor changes, I wanted to pull that logic out into one function I could reuse for both. So, I built this section:</p><pre>def parse_range(spec, convert):<br>    if &quot;,&quot; in spec:<br>        return [convert(p) for p in spec.split(&quot;,&quot;)]<br>    elif &quot;-&quot; in spec:<br>        start_str, end_str = spec.split(&quot;-&quot;)<br>        start = convert(start_str)<br>        end = convert(end_str)<br>        return [convert(i) for i in range(int(start), int(end) + 1)]<br>    else:<br>        return [convert(spec)]</pre><p>The part that was genuinely new to me here was the convert parameter. I had never passed a function in as an argument before, the way you’d pass a string or a number. But apparently in Python, a function is just an object like anything else, so you can hand one to another function without calling it, and have it get called later, inside. So, when I call it like this:</p><pre>targets = parse_range(ip_arg, ipaddress.ip_address)<br>ports = parse_range(port_arg, int)</pre><p>The same parse_range function handles both IPs and ports, just by swapping out what convert points to. Inside the function wherever I wrote convert(p), it’s really calling whichever function got passed in, ipaddress.ip_address(p) in one case, int(p) in the other, without parse_range itself needing to know or care which one it’s working with.</p><p>For actually splitting an IP range like 192.168.1.220–192.168.1.230, I had to figure out a new trick, since IPs don’t increment like plain numbers the way ports do. I found out that the ipaddress module lets you convert any IP address into its underlying raw integer with int(), since under the hood every IPv4 address really is just a 32-bit number. So, I could do int(start) and int(end), range() between those two plain integers exactly like I already knew how to do with ports, and then convert each resulting number back into a proper IP with ipaddress.ip_address(i) again.</p><p>Once I had this one shared function, the rest of the script followed the same two-stage structure I built in the ping sweep exercise before this one — first ping every target IP to see which ones are actually alive, using a ThreadPoolExecutor, and only once that’s completely finished, move on to port-scanning just the hosts that responded:</p><pre>with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:<br>    ping_futures = {executor.submit(ping_host, ip): ip for ip in targets}<br>    alive_hosts = []<br>    for future in concurrent.futures.as_completed(ping_futures):<br>        ip = ping_futures[future]<br>        if future.result():<br>            alive_hosts.append(ip)</pre><p>I used a dictionary here instead of a plain list of futures because ping_host only returns True or False; it doesn’t return which IP it was testing. So, the dictionary maps each Future back to the IP it belongs to, meaning once a future finishes I can look up ping_futures[future] to find out which IP that result is actually for.</p><p>The port-scanning stage then only runs against alive_hosts, nested in a loop over every port for every alive IP:</p><pre>with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:<br>    port_futures = {}<br>    for ip in alive_hosts:<br>        for port in ports:<br>            future = executor.submit(scan_port, str(ip), port)<br>            port_futures[future] = (ip, port)</pre><p>I kept these as two separate ThreadPoolExecutor blocks on purpose, rather than trying to combine everything into one pass. The reasoning is that I need to know which hosts are alive before I even start port-scanning them, there’s no point spending time and connections scanning ports on a host that’s already dead. So, the ping sweep has to fully finish (its block has to close) before the port-scanning stage even starts.</p><p>I tested it with a small range covering my Metasploitable box plus some IPs around it, along with a handful of ports:</p><p>python learningtoScanner.py 192.168.1.220–192.168.1.230 21,22,80,445</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*L80FWDVhv2uguWGbINbivA.png" /></figure><p>python learningtoScanner.py 192.168.1.1,192.168.1.223 0–1024</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*O4IESCb_NjxVkyN8yCB5xQ.png" /></figure><p>I realized that the tests were sometimes inconsistent, possibly because we had only been sending one packet and waiting for one second for each device. Instead, I changed that part to sending 4 packets and waiting 2 seconds, and the results got more consistent.</p><pre>[&quot;ping&quot;, &quot;-c&quot;, &quot;4&quot;, &quot;-W&quot;, &quot;2&quot;, str(ip)],</pre><p>P.S. For this last test, I had already turned off my Metasploitable, so that won’t show up in this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*jSHiF0Cs-46VPvs7lkfWdQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=850cd895861b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Walkthrough — NIST — Rhino Hunt]]></title>
            <link>https://medium.com/@aa2812061/walkthrough-nist-rhino-hunt-1089084e7e15?source=rss-a4dad81bab85------2</link>
            <guid isPermaLink="false">https://medium.com/p/1089084e7e15</guid>
            <category><![CDATA[nist]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[digital-forensics]]></category>
            <dc:creator><![CDATA[Luffytaroouu]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 13:09:52 GMT</pubDate>
            <atom:updated>2025-08-26T13:09:52.280Z</atom:updated>
            <content:encoded><![CDATA[<h3>Walkthrough — NIST — Rhino Hunt</h3><h3>1. Introduction</h3><p>This report is an investigation for a case in the city of New Orleans where possession of nine or more unique rhinoceros image is a serious crime. A network administrator saw traces of suspicious activities and alerted the police. The evidence received by the digital forensic investigator is a CD-ROM which contains three network traces that have been provided by the network administrator and a dd image of the USB key. The tools that are used in the process of this investigation are Wireshark, Autopsy, Kraken, jphideseek, Stegdetect.</p><h3>1.1 Current Scenario:</h3><p>The city of New Orleans passed a law in 2004 making possession of nine or more unique rhinoceros’s images a serious crime. The network administrator at the University of New Orleans recently alerted police when his instance of RHINOVORE flagged illegal rhino traffic. Evidence in the case includes a computer and USB key seized from one of the University’s labs. Unfortunately, the computer had no hard drive. The USB key was imaged and a copy of the dd image is on the CD-ROM you’ve been given.</p><p>In addition to the USB key drive image, three network traces are also available — these were provided by the network administrator and involve the machine with the missing hard drive. The suspect is the primary user of this machine, who has been pursuing his Ph.D. at the University since 1972.</p><h3>1.2 Aims:</h3><p>The aim of this report is to digitally investigate the evidences provided by the network administrator and determine if there was any crime that had occurred and if it had who was the culprit.</p><h3>1.3 Objectives:</h3><p>The objectives of the report is to find out at least nine images of rhino from the acquired evidences and to answer the following questions:  Who gave the accused a telnet/ftp account?</p><ul><li>What’s the username/password for the account?</li><li>What happened to the hard drive in the computer? Where is it now?</li><li>What happened to the USB key?</li><li>What is recoverable from the dd image of the USB key?</li><li>Is there any evidence that connects the USB key and the network traces? If so, what?</li></ul><h3>2. Investigation with Demonstration:</h3><p>There are two phases in this part of the report in the first phase the resources that are required for this investigation are gathered and listed. In the second phase the demonstration of the steps of the investigation of the acquired evidences are shown step wise.</p><h3>2.1 Resources gathering and listing:</h3><p>The tools, files and webpages that are required for the forensic investigation are gathered and kept in a directory as following:</p><ul><li>Wireshark</li><li>Kraken</li><li>Autopsy</li><li>Jphide and seek</li><li>Stegdetect</li><li>The disk image file(which contains)</li><li>rhino.log</li><li>rhino2.log</li><li>rhino3.log</li><li>RHINOUSB.dd</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0QsUAVXphH8trr4I" /></figure><p><em>Figure 1: Gathering all the required tools, applications and evidence.</em></p><p>Along with the tools that are mentioned above a few web tools are also required in the process of the investigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lqz8H8NR1WgoP5zU" /></figure><p><em>Figure 2: Whoislookup (whois, 2021)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ShAGkY56gTyDvY6z" /></figure><p><em>Figure 3: MD5 file checksum (emn178, 2021)</em></p><h3>2.1.1 Short Description of the tools used:</h3><h4>2.1.1.1 Wireshark:</h4><p>Wireshark is the most popular and commonly used network protocol analyser in the world. It is the de facto (and frequently de jure) standard across many commercial and non-profit organizations, government agencies, and educational institutions because it allows you to observe what’s going on your network at a microscopic level. Wireshark development flourishes thanks to volunteer contributions from networking specialists all across the world, and is a continuation of Gerald Combs’ 1998 initiative. (Wireshark, 2021)</p><h4>2.1.1.2 Kraken:</h4><p>Without a flashy GUI for optimal efficiency, Kraken is a free, fast, and compact RAR, ZIP, 7-Zip, and Hash password recovery application for Windows. No trial, no limits! (Kraken, 2021)</p><h4>2.1.1.3 Autopsy:</h4><p>Autopsy is a graphical interface to The Sleuth Kit and other digital forensics tools, as well as a digital forensics platform. Law enforcement, military, and business examiners utilize it to figure out what transpired on a computer. It may also be used to recover photographs from the memory card of your camera. (Autopsy, 2021)</p><h4>2.1.1.4 Stegdetect:</h4><p>Stegdetect is a program that detects steganographic material in photos automatically. It can detect a variety of steganographic techniques used to incorporate hidden information in JPEG images. (Ellis, 2013)</p><h4>2.1.1.5 Whoislookup:</h4><p>Whois lookup is an online tool that provides information regarding a domain name, like example.com. It may contain details such as domain ownership, registration location and date, expiration date, and nameservers allocated to the domain. (mediatemplate, 2021)</p><h4>2.1.1.6 MD5 file checksum:</h4><p>An MD5 checksum is a mathematical procedure that is usually a set of 32character hexadecimal letters and numbers generated with a tool on a file. These figures are generated with the help of special software that uses a “cryptographic hash algorithm yielding a 128-bit (16-byte) hash result.” It’s used to encrypt various kinds of files, not just ZIP archives and EXE installers. Even a text or document file can be given an MD5 sum. The perfect match of MD5 checksum values ensures that a file’s digital integrity and security have not been compromised by anyone, and that it is an exact copy of the original file. (support, 2017)</p><h4>2.1.1.7 Jphide and seek:</h4><p>JPHS is an abbreviation for Jpeg hide and seek. Allan Latham’s program is designed to work with JPEG files and lossy compression, and it comes in Windows and Linux versions. There is no need to install anything. JPHS consists of two programs, JPHIDE and JPSEEK, that allow you to hide a message file within a jpeg visual image. JPHIDE.EXE is a program that hides a data file within a jpeg image. JPSEEK.EXE is a program that retrieves files that have been hidden by JPHIDE.EXE. JPHSWIN.EXE is the Windows version of the two programs mentioned, and it performs the same functions. The hidden file is distributed in the jpeg image by JPHIDE and JPSEEK, minimizing both the visual and statistical consequences. The discrete cosine transform coefficients used by the jpeg algorithm are overwritten by JPHS via least significant bit overwriting. Simple programs that store hidden data in low order bits may cause the jpeg image to be statistically different from the typical jpeg file, allowing the hidden content to be easily recovered. To choose where to place the bits of the hidden file, JPHIDE employs the Blowfish crypto method for least significant bit randomization and encryption. To start the process, the application will ask for a pass phrase. Although the software “encrypts” the hidden file, it is advised that it be encrypted (by another application) before being included into the jpeg file. With negligible visual and statistical effect, up to 10% can be added into a jpeg file. If the original jpeg file is available, a hidden file can always be found, albeit knowing the stego tool and the pass word is required to extract the content. (athabascau, 2021)</p><h3>2.2 Demonstration of the investigation:</h3><h3>2.2.1 Using Wireshark to check the network log files:</h3><p>Wireshark was used on the network logs that was provided by the network administrator so that the network logs could be investigated for any criminal activities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pgGon6Bpfb9nAA6Y" /></figure><p><em>Figure 4: Opening wireshark</em></p><h4>2.2.1.1 Investigation of rhino.log file</h4><p>Rhino.log is the first file that will be investigated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b5otsL60yqVV7Wsz" /></figure><p><em>Figure 5: rhino.log username and password</em></p><p>After the rhino1.log was listed on the basis of protocols we could see a username and password for an ftp account being exchanged in the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wJ3SAs0dgo2WOM-L" /></figure><p><em>Figure 6: Following the packet that had the username</em></p><p>After following the packet that was being exchanged for the ftp login we could see the user gnome logging in and the password and username of the account. Along with a connection and transfer of rhino1.jpg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iL1NBp-rMyq-syNu" /></figure><p><em>Figure 7: Filtering the packet according to ftp-data and transferring of rhino1.jpg</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X9l06ikI8gjReYjV" /></figure><p><em>Figure 8: rhino3.jpg spotted in the ftp-data stream</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BVqcPDUb6V_8Di1t" /></figure><p><em>Figure 9: contraband.zip spotted in the ftp-data stream</em></p><p>After noticing that there was a file being transferred in the ftp connection we filtered the packets according to ftp-data and we could see rhino1.jpg, rhino3.jpg and contraband.jpg being transferred in the stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*NechTTPAfl2rcyCw" /></figure><p><em>Figure 10: Exracting rhino1.jpg from the network stream</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9p4KIDn8mOnu3-Ic" /></figure><p><em>Figure 11: Extracting rhino3.jpg from the network stream</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fo3yxqBo5k1fPKsd" /></figure><p><em>Figure 12: Extracting Contraband.zip from the network stream</em></p><p>After we spotted rhino1.jpg, rhino3.jpg and contraband.zip files in the ftp-data stream we saved them and opened and checked them to see what they were.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cq_BxLTZlqN4dlUJ" /></figure><p><em>Figure 13: Image in rhino1.jpg file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gXm_PghPxr9HzUXO" /></figure><p><em>Figure 14: Image in rhino3.jpg file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*CxfIRzVuWiE8gKL6" /></figure><p><em>Figure 15: Contraband.zip file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X_ofoMhRBNeZOlJE" /></figure><p><em>Figure 16: Password in contraband.zip file</em></p><p>After extracting the rhino1.jpg, rhino3.jpg and contraband.zip files they were opened and checked images of rhino could be seen in rhino1.jpg and rhino3.jpg. rhino2.jpg file could be seen in the contraband.zip file however as the file was password protected the exact contains of the contraband.zip file couldn’t be seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rx_oULBO1_0HR-nN" /></figure><p><em>Figure 17: Analysing the telnet protocol packets</em></p><p>As we analysed the packet stream more, telnet protocol could be seen. Upon closer examination of the telnet packets, the username and password could be seen in the telnet packets. A failed attempt to change the password and username of the account could also be seen. Also the IP Address of the sender could be seen. After checking the IP Address that was found was checked in whoislookup it could be seen that the IP belonged to United States New Orleans University of New Orleans. No more evidence could be found in the rhino.log file so the investigation of rhino2.log was started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MAUYdzVMuN2ubHE1" /></figure><p><em>Figure 18: Contains of telnet packet 1</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-SL3A0Xui7xu3Cjw" /></figure><p><em>Figure 19: Contains of telnet packet 2</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XWnCj7rTbCKPSETr" /></figure><p><em>Figure 20: Contains of telnet packet 3</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kDIunN96p2G1nuBt" /></figure><p><em>Figure 21: Checking the found ip in whoislookup</em></p><h4>2.2.1.2 Investigation of rhino2.log file</h4><p>Rhino2.log file was investigated using wireshark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I-lDDKoSEIJF5YKl" /></figure><p><em>Figure 22: images.gif file</em></p><p>After opening the rhino2.log file in wireshark an HTTP data transfer of images/logo.gif file could be seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uqrUYz6ig-AZI37e" /></figure><p><em>Figure 23: Export HTTP object list</em></p><p>After spotting the images/logo.gif file, wireshark was used to extract all the files that were transferred in the HTTP data transfer. Among the files listed above most of the files were useless and empty files however upon extracting rhino4.jpg and rhino5.gif we found more evidences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*mDrdfvcgWxSsSgOM" /></figure><p><em>Figure 24:Extracting rhino4.jpg</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*UJYzc383v-fEf0fN" /></figure><p><em>Figure 25: Extracting rhino5.gif file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bHLvjyAnydUC9y4q" /></figure><p><em>Figure 26: Image in rhino4.jpg file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*z_VU4RpTVduu6CJo" /></figure><p><em>Figure 27: Image in rhino5.gif file</em></p><p>Within the rhino4.jpg and rhino5.gif file, two more images of rhino could be seen. These images were saved along with the other image files that were found.</p><p>Nothing more could be found in the rhino2.log file so the investigation of rhino3.log file was investigated.</p><h4>2.2.1.3 Investigation of rhino3.log file</h4><p>Rhino3.log file was investigated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vB4T0mpG8CI9jf2c" /></figure><p><em>Figure 28: rhino.exe file</em></p><p>After spotting a rhino.exe file in the HTTP data stream we checked all the files that were transferred in the HTTP stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7eJAQu7WhrJsj2Hx" /></figure><p><em>Figure 29: rhino3 export HTTP object list</em></p><p>Most of the files in the export HTTP object list turned out to be useless in the investigation however the rhino.exe file seemed useful so it was extracted and checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S5dOCDDwRNxM91fu" /></figure><p><em>Figure 30: Trying to open rhino.exe</em></p><p>Upon trying to open the rhino.exe file, it could be seen that this application was for Windows XP or older version of windows but wouldn’t open in newer version. As nothing more was found in the rhino3.log file the contraband.zip file was investigated.</p><h3>2.2.2 Use of Kraken tool:</h3><p>As we saw previously the contraband.zip file was password protected, so we used the kraken software to find out the password so we could extract the data it contains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GwBj5VHUZaC1nAE_" /></figure><p><em>Figure 31: Keeping the contraband.zip file in recovery folder</em></p><p>The contraband.zip file was copied and pasted in the recovery folder of the kraken tool so that the password of the zip file could be extracted using the kraken tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BOmtYsxQziPN_-r5" /></figure><p><em>Figure 32: Opening the kraken tool</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J9vvJ8ut1doCTJG8" /></figure><p><em>Figure 33: Selecting the dictionary option</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sgIpdeodmZyhpGWp" /></figure><p><em>Figure 34: Extracting the password of Contrband.zip file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*apTzhCHlcFc7kU5P" /></figure><p><em>Figure 35: Recovered password for contraband.zip</em></p><p>The kraken tool was used to recover the password of the contraband.zip file using a dictionary that contained a number of common passwords. After the application was run the recovered password was “monkey”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t6X2pivR0MLL_5c8" /></figure><p><em>Figure 36: Extracting the data from the contraband.zip file using the recovered password</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FRJn3agZdVLWms10" /></figure><p><em>Figure 37: Image in the rhino2.jpg file</em></p><p>After the contraband.zip file was extracted we found a rhino2.jpg file inside it. When the rhino2.jpg file was opened an image of a rhino could be found inside the file. This was added to the list of other evidence’s that were found.</p><h3>2.2.3 Extracting the hash values of the files</h3><p>All the MD5 values of the evidences that were found up to this point were collected and stored in a file separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J84Ix8YDcCRFBeg3" /></figure><p><em>Figure 38: MD5 of rhino 1</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*sCvmMmAzMwviHKvi" /></figure><p><em>Figure 39: MD5 of rhino2</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/0*6TE44AsRVJn91wBJ" /></figure><p><em>Figure 40: MD5 of rhino3</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*15Hu1kraQ-EyiKbp" /></figure><p><em>Figure 41: MD5 of rhino4</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/0*6vOf6wHk_-uwn3Tv" /></figure><p><em>Figure 42: MD5 of rhino5</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UhOke4vjHOjXrgwj" /></figure><p><em>Figure 43: All the MD5 values found</em></p><h3>2.2.4 Using Autopsy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x1NnqzZVvpJ5knT9" /></figure><p><em>Figure 44: Images found in the RHINOUSB.dd</em></p><p>After running the autopsy tool in the RHINOUSB.dd file we found 9 images. Among the 9 images 4 of the images were rhino images. These images were extracted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qrhDZu6lMlqhzrAv" /></figure><p><em>Figure 45: rhino image in RHINOUSB.dd 1</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qC3JF0pL_CwHfk6v" /></figure><p><em>Figure 46: rhino image in RHINOUSB.dd 2</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dBIXDnXBdpGmUNDI" /></figure><p><em>Figure 47: rhino image in RHINOUSB.dd 3</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6O-zn_vuLEntKmVX" /></figure><p><em>Figure 48: rhino image in RHINOUSB.dd 4</em></p><p>After we found four more rhino images in the RHINOUSB.dd image we extracted those images and saved them as rhino6.jpg, rhino7.jpg, rhino8.jpg and rhino9.jpg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QqLxbkHSTV71nXaC" /></figure><p><em>Figure 49: Image in rhino6.jpg file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6C2qA8QwyVFuksO2" /></figure><p><em>Figure 50: Image in rhino7.jpg file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5DVYZCPuoAIL_Ogu" /></figure><p><em>Figure 51: Image in rhino8.jpg file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C-cwt9dvNxEGMRp8" /></figure><p><em>Figure 52: Image in rhino9.jpg file</em></p><p>Along with the images we also found a text file that was recovered from the RHINOUSB.dd iso image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fIhRQ6ILh9vBlZMr" /></figure><p><em>Figure 53: Suspicious text found inside RHINOUSB.dd</em></p><p>The suspicious text found inside the RHINOUSB.dd were as follows:</p><p>“Rhino pictures illegal? Makes me sick. I “hid” the photos…hehehehe. Apparently, if there are less than 10 photos, it’s no big deal.”</p><p>“OK. Things are getting a little weird. I zapped the hard drive and then threw it into the Mississippi River. I’m gonna reformat my USB key after this entry, but try not to destroy the good stuff. I need to change the password on the gnome account that Jeremy gave me. I can probably just do that at Radio Shack.”</p><p>2.2.5 Extracting the hash value of the files recovered from RHINOUSB.dd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/0*xKmFlonhjjHt6Uma" /></figure><p><em>Figure 54: MD5 of rhino6</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/0*ql0ABkPn9uNyW_ry" /></figure><p><em>Figure 55: MD5 of rhino7</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*68pPAbae45m3plcN" /></figure><p><em>Figure 56: MD5 of rhino8</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*ILp_-p14qB3jI6UV" /></figure><p><em>Figure 57: MD5 of rhino9</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*malMjdKPlFADk0_q" /></figure><p><em>Figure 58: MD5 values of the files recovered from RHINOUSB.dd</em></p><p>After extracting the hash values of the images from RHINOUSB.dd we can notice that the hash value of rhino7 and rhino2 are same.</p><h3>2.2.6 Using steghide and seek</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/0*rMMZVbXTyuWp6Qz1" /></figure><p><em>Figure 59: Using stegdetect on all nine of the image files found in RHINOUSB.dd</em></p><p>After using the stegdetect on the image files that were recovered from the RHINOUSB.dd. It could be seen that four of those files seemed suspicious. These files were further investigated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*Qhhu2bOu0TR3UiV_" /></figure><p><em>Figure 60: Finding hidden images inside the image and their password</em></p><p>After using stegbreak in the files two files were found that used the steganography process to hide another file inside of them. Their passwords could also be extracted using the stegbreak tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*xVFcRRZR0AUEAbJ8" /></figure><p><em>Figure 61: Using jpseek to recover the file hidden inside f0104520.jpg</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*74tc7_myrJRm-90U" /></figure><p><em>Figure 62: Image in rhino10.jpg file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*kbHYk8yq1O9y172m" /></figure><p><em>Figure 63: Extracting image hidden in f0103704.jpg</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bh7NV3Q-qQ_bboJr" /></figure><p><em>Figure 64: Image in rhino11.jpg file</em></p><p>After investigating the images with hidden files inside them, jpseek tool was used to extract the hidden file along with the password that was extracted using stegbreak. The hidden files were saved as rhino10.jpg and rhino11.jpg. After opening these files two more images of rhino could be found that had been hidden using steganography tools.</p><h3>3. Findings of the investigation</h3><h3>3.1 Who gave the accused a telnet/ftp account?</h3><p>Jeremy gave the accused the telnet/ftp account.</p><h3>3.2 What’s the username/password for the account?</h3><p>The accounts username and password are “gnome” and “gnome123” respectively.</p><h3>3.3 What relevant file transfers appear in the network traces?</h3><p>The relevant file transfers that appear in the network are;</p><p>Rhino1.jpg</p><p>Rhino2.jpg found in contraband.zip</p><p>Rhino3.jpg</p><p>Rhino4.jpg</p><p>Rhino5.gif</p><p>Rhino.exe</p><h3>3.4 What happened to the hard drive in the computer? Where is it now?</h3><p>The hard drive was zapped and was thrown into the Mississippi river.</p><h3>3.5 What happened to the USB key?</h3><p>The USB key was reformatted.</p><h3>3.6 What is recoverable from the dd image of the USB key?</h3><p>Nine image files and a text file were recoverable from the image of the USB key.</p><h3>3.7 Is there any evidence that connects the USB key and the network traces? If so, what?</h3><p>The evidence that connects the USB key and the network traces is that the MD% hash file extracted from rhino2.jpg which was found from rhino.log and rhino7.jpg(f0105864.jpg) which was found in the USB key image file are the same i.e. ed870202082ea4fd8f5488533a561b35.</p><h3>4. Conclusion</h3><p>This report concludes that the suspect is the criminal, he had transferred the files and the rhino images which were illegal to possess in the city of New Orleans. The USB key image and the network traces could be connected as there were files that had the same MD5 hash value in the two. As this proved that the suspect possessed 9 or more rhino images the suspect could be declared guilty.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1089084e7e15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Walkthrough — NIST — Forensic Image Test Image]]></title>
            <link>https://medium.com/@aa2812061/walkthrough-nist-forensic-image-test-image-d7909065362f?source=rss-a4dad81bab85------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7909065362f</guid>
            <dc:creator><![CDATA[Luffytaroouu]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 03:14:48 GMT</pubDate>
            <atom:updated>2025-08-26T03:14:48.888Z</atom:updated>
            <content:encoded><![CDATA[<h3>Walkthrough — NIST — Forensic Image Test Image</h3><p>NIST — Forensic Image Test Image</p><p>Date: February 25th 2025</p><p>Investigation done by Luffytaroouu</p><p>Introduction:</p><p>This forensic investigation is being conducted in an encase image file that is created by National Institute of Standards and Technology (NIST). It is designed to help evaluate and educate users about forensic tools and image analysis. NIST has provided tasks to be solved through the investigation. The tools that are used in the process of this investigation are Autopsy, FTK Imager, Email Client (Thunderbird), gdisk, fdisk, mxtoolbox, and hashing tools.</p><h3>Q1: What is the destination time zone offset in from UTC for the following email received by Jimmy Wilson “447018D5–00000006.eml” Select one:</h3><p>a. +04:00</p><p>b. -07:00</p><p>c. -08:00</p><p>d. -05:00</p><p>e. -09:00</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XQ5Iqel1ss2LsgMF" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yL4YGaInCegtOF1D" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jbk-5NZqAF0Dfrmz" /></figure><p>Ans: UTC -08:00</p><h3>Q2: What is the total capacity in bytes (decimal) of the partition labeled “J. Wilson” found in the System.vhd file?</h3><p>Select one:</p><p>a. 253,755,392</p><p>b. 209,715,200</p><p>c. 230,686,720</p><p>d. 681,574,400</p><p>e. 734,003,200</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2eXuweRDUbsFQrKq" /></figure><p>At this point I got confused, I checked all the texts inside the hex for each partition and noticed that J. Wilson listed on vol 7 so was reliant on that being the needed partition. But</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HfZqUzyZuMVuMuI7" /></figure><p>1331200 x 512 = 681,574,400</p><p>Ans: 681,574,400</p><h3>Q3: What was the date and time the following email received by Jimmy Wilson “447018D5- 00000006.eml” was originally sent?</h3><p>Select one:</p><p>a. Sun, 16 February 2014 10:55:09 -05:00</p><p>b. Sun, 16 February 2014 07:55:09 -05:00</p><p>c. Sun, 16 February 2014 12:55:09 -05:00</p><p>d. Sun, 16 February 2014 11:55:09 -05:00</p><p>e. Sun, 16 February 2014 13:55:09 -05:00</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gn5BLYWkhpjb3x58" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nu1qVPQx5iaUozaZ" /></figure><p>The email was originally sent at Sun, 16 Feb 2014 12:55:09 -0500</p><h3>Q4: The physical disk contains a Virtual Hard Drive which is greater than 10MB in size, the full name of the file is: system.vhd</h3><p>Select one:</p><p>a. True</p><p>b. False</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*NGunSswa7VObU7xZ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/0*NdmSzXu8N8Y91Pet" /></figure><p>True</p><h3>Q4: The disk GUID (in hex) of the physical disk is: 6FAE8D386C441743AE3298C4BDE04830.</h3><p>Select one:</p><p>· True</p><p>· False</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*8webZ3KlM8zHEuk_" /></figure><p>Disk Identifier (GUID) is 82DA3DC6-AA66–4251–8180–975DE8C4769E<br>which is different from 6FAE8D386C441743AE3298C4BDE04830 so No, the GUID doesn’t match.</p><h3>Q5: What is the cluster size in bytes within the second partition of the physical disk?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*76ei-oG8z9Lw8b9N" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GdNkDzlcT4Fdp0vl" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*y0-gFeVPDngVSnE8" /></figure><p>The cluster size is 4096.</p><h3>Q6: On February 20, 2014 @ 17:02:35 UTC -00:00, what was the system up time in seconds is: 9,634.</h3><p>Select one:</p><p>a. True</p><p>b. False</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TjjMbMb28zzrwv9h" /></figure><p>As it can be seen the logs are saved in EDT, the difference between EDT and UTC is -5 hrs as the questions asks us about February 20, 2014 @ 17:02:35 UTC -00:00, it would be 12:02:35 in EDT so, it is true, the uptime is 9634 seconds as per the system logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3KX6fgRMXWaX3fPt" /></figure><h3>Q7: The MD5 hash value of the pdf.pdf file is: C1F95108A34228535A9262085E784D7C3E27FC68.</h3><p>Select one:</p><p>· True</p><p>· False</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cp3naqLi-r85Qmfm" /></figure><p>No the MD5 hash of the file isn’t C1F95108A34228535A9262085E784D7C3E27FC68 but 8bd6509aba6eafe623392995b08c7047</p><h3>Q8: The user account Jimmy Wilson has his logon password enabled and the password hint is safeone.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eCZ3Lc-wFkpJ1lAP" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OeaItP6duc-HXN59" /></figure><p>Yes the password is enabled and the hint is safe one.</p><h3>Q9: What is the partitioning format (Schema) of the physical disk?</h3><p>Select one:</p><p>a. None of the other answers are correct.</p><p>b. GPT</p><p>c. The Physical disk is not partitioned.</p><p>d. MBE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*1pR5PTmwzi2tD6US" /></figure><h3>Q10: The destination IP Address for the following email received by Jimmy Wilson “447018D5–00000006.eml” is: 10.221.48.196</h3><p>Select one:</p><p>· True</p><p>· False</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2-2hz6enL8EvFnG0" /></figure><p>Ans: True</p><h3>Q 11: The 2nd partitions unique GUID (in hex) of the physical disk is:</h3><h3>423FDC8AA701EE46AF5A70C06738E819</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DVDEuX5EiNtvXlOT" /></figure><p>False</p><h3>Q12: What is the logical size in bytes (decimal) of the pdf.pdf file?</h3><p>Select one:</p><p>a. 444,332</p><p>b. 433,994</p><p>c. 395,232</p><p>d. 253,283</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tNyq870AKUWABmIi" /></figure><p>Ans: 433994</p><h3>Q13: The User account BillyBob sent the following files to the $recyclebin: New Price List.txt and New Price List Encoded.</h3><p>Select one:</p><p>· True</p><p>· False</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JscmpkmF1MEvEUSo" /></figure><p>Ans: True</p><h3>Q14: What is the logical file size in bytes (decimal) of the PLEAS.txt file?</h3><p>Select one:</p><p>a. 110,592</p><p>b. 122,336</p><p>c. 122,880</p><p>d. 108,227</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A3AwUbi8Ik0mRx1x" /></figure><p>Ans: 122336</p><h3>Q15: Provide the full name of the User that has the RID number 0x3EB:</h3><p>Select one:</p><p>a. Administrator</p><p>b. Betty Boop</p><p>c. Joe T. Nameless</p><p>d. BillyBob</p><p>e. Guest</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*li9ovsPVk_4AKCM6" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L-olWFoPi4xB3nhj" /></figure><p>Ans: Joe T. Nameless</p><h3>Q16: When was the last log-in date and time for the User “Jimmy Wilson”?</h3><p>Select one:</p><p>a. February 18, 2014 12:38:16 UTC -00:00</p><p>b. January 19, 2014 06:22:12 UTC -00:00</p><p>c. March 03, 2014 11:11:11 UTC -00:00</p><p>d. None of these times are correct</p><p>e. February 19, 2014 13:30:58 UTC -00:00</p><p>f. April 01, 2014 00:00:01 UTC -00:00</p><p>g. February 17, 2014 17:38:22 UTC -00:00</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w2cSnh_BlwiXeMtE" /></figure><p>It shows that the last logged in time is 2/19/2014 8:30:58 AM EDT which converted to UTC is February 19, 2014 13:30:58 UTC -00:00 so the answer is D.</p><h3>Q17: The following individuals: jose.Badguy@hushmail.com, robert.ripoff@gmx.com sent emails to the User Jimmy Wilson?</h3><p>Select one:</p><p>· True</p><p>· False</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BBcTDxrOMK5r1vtI" /></figure><p>Ans: True</p><h3>18: What program did the User Jimmy Wilson have set to run when he logged on to the computer?</h3><p>a. None of the other answers are correct</p><p>b. Notepad.exe</p><p>c. StinkyNot.exe</p><p>d. MSAccess.exe</p><p>e. MSWord.exe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tjwMuIClrGohvLLc" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gxfUis34hA84vGJv" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vsg90t9wxV_IJnP2" /></figure><p>Ans: StikyNot.exe</p><h3>Q19: The SHA1 hash value for the AISB08.pdf file is: BDEBF09E8B2D404D1C483C3EBFB8AD37C780D909</h3><p>Select one:</p><p>· True</p><p>· False</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fpu566eYdP__T63v" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zMx6qqdxAWFIBlTL" /></figure><p>Yes the hash is the same. Hence, the Answer is true</p><h3>20: What encryption programs were used on this computer?</h3><p>a. Veracrypt/BitLocker</p><p>b. BitLocker/Veracrypt</p><p>c. File Vault/Truecrypt</p><p>d. BCTextEncoder/Veracrypt</p><p>e. No encryption programs were used</p><p>f. Truecrypt/BCTextEncoder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IY2mIFFxPcDFTj6X" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jHrK8GPoDlqx1_Yl" /></figure><p>Ans: Truecrypt/BCTextEncoder</p><h3>Q22: The SHA1 hash value for the Card Printers.htm file is: F6CF04DB3D1BA828E375BBFE988876CE06164126</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LPA6LfGoiusvfhMn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bJJA_n1qntjc-6D9" /></figure><p>Ans: False</p><h3>Q23: What search engine did the User “Jimmy Wilson” use to search for: how to steal identities? Select one:</h3><p>a. Yahoo</p><p>b. Bing</p><p>c. DuckDuckGo</p><p>d. Dogpile</p><p>e. Google</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P5_Gvl2GDIauH6-P" /></figure><p><strong>Ans: Bing</strong></p><h3>Q24: What is the last Date/Time the User “Jimmy Wilson” last ran the Windows Mail Application?</h3><p>Select one:</p><p>a. Sat, 25 January 2014 15:27:51 -00:00 UTC</p><p>b. Sat, 25 January 2014 19:27:51 -00:00 UTC</p><p>c. Sat, 25 January 2014 18:27:51 -00:00 UTC</p><p>d. Sat, 25 January 2014 17:27:51 -00:00 UTC</p><p>e. Sat, 25 January 2014 16:27:51 -00:00 UTC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L7CflMMki7JblgJE" /></figure><p>Ans: 25 January 2014 18:27:51 -00:00 UTC</p><h3>Q25: What is the SHA1 hash value of the Physical Disk?</h3><p>Select one:</p><p>a. a1102c70a50768b588225fdcad6efa5d5d57341b</p><p>b. None of the other answers are correct.</p><p>c. 5fdcad6efa5d5d57341ba1102c70a50768b58833</p><p>d. 68b588225fdcad6efa5d5d5734b1a1102c70a507</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MEfpPMWn7L49bBst" /></figure><p>The SHA 1 hash value of the physical disk is a1102c70a50768b588225fdcad6efa5d5d57341b.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7909065362f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>