Search code examples
pythonpython-3.xcommand-linewindows-10powershell-2.0

How can I interact with the cmd prompt from python


I am writing a very short program to check MD5 Sums for file security

I would like to take a file path from the user and the expected output from the checksum from the command "CertUtil -hashfile MD5", where will be the filepath input from the user, I would then like to take the output of the command prompt as a string to compare to the expected output that the user has specified. Is this possible? If so, how can I modify the code below to allow the filepath to be submitted as a variable and take an output from the command prompt?

I am coding in python 3.9.0 64bit on Windows 10 and would like to avoid installing and additional libraries unless absolutely necessary

'''

#CheckSumChecker! By Joseph
import os
#User file input
data = input("Paste Filepath Here: ")
correct_sum = ("Paste the expected output here: ")
#File hash is checked using cmd "cmd /k "CertUtil -hashfile filepath MD5"
os.system('cmd /k "CertUtil -hashfile C:\Windows\lsasetup.log MD5"')
if correct_sum == cmd_output:
    print("The sums match!" correct_sum "=" cmd_output)
else:
    print("The sums don't match! Check that your inputs were correct" correct_sum "is not equal to" cmd_output)

'''


Solution

  • You can use subprocess.check_output. (There were some other mistakes in your code I've fixed here.)

    import subprocess
    
    input_path = input("Paste Filepath Here: ")
    correct_sum = input("Paste the expected output here: ")
    output = (
        subprocess.check_output(
            ["CertUtil", "-hashfile", input_path, "MD5",]
        )
        .decode()
        .strip()
    )
    print("Result:", output)
    if correct_sum == output:
        print("The sums match!", correct_sum, "=", cmd_output)
    else:
        print(
            "The sums don't match! Check that your inputs were correct",
            correct_sum,
            "is not equal to",
            cmd_output,
        )
    

    Or, to avoid using CertUtil at all, use the built-in hashlib module.

    You will have to take some care not to read the entire file into memory at once...

    import hashlib
    input_path = input("Paste Filepath Here: ")
    correct_sum = input("Paste the expected output here: ")
    
    hasher = hashlib.md5()
    with open(input_path, "rb") as f:
        while True:
            chunk = f.read(524288)
            if not chunk:
                break
            hasher.update(chunk)
    output = hasher.hexdigest()
    print("Result:", output)
    if correct_sum == output:
        print("The sums match!", correct_sum, "=", cmd_output)
    else:
        print(
            "The sums don't match! Check that your inputs were correct",
            correct_sum,
            "is not equal to",
            cmd_output,
        )