如何与python中的cmd提示符交互

2024-09-19 14:17:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个非常简短的程序来检查MD5总和的文件安全性

我想从用户获取文件路径,从命令“CertUtil-hashfile MD5”获取校验和的预期输出,其中将是用户输入的文件路径,然后我想将命令提示符的输出作为字符串,与用户指定的预期输出进行比较。这可能吗?如果是这样,我如何修改下面的代码以允许将filepath作为变量提交并从命令提示符获取输出

我在Windows10上使用Python3.9.0 64位编码,除非绝对必要,否则我希望避免安装和附加库

'''

#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)

'''


Tags: 文件用户路径cmdinputoutputosmd5
1条回答
网友
1楼 · 发布于 2024-09-19 14:17:12

您可以使用subprocess.check_output。(我在这里修复了代码中的一些其他错误。)

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,
    )

或者,为了避免使用CertUtil,请使用内置的hashlib模块

您必须注意不要将整个文件一次读入内存

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,
    )

相关问题 更多 >