====== Comparación de Archivos de Texto con Python y PowerShell ======
===== Comparación por hash =====
$path = "C:\Users\unapa\OneDrive - TandemStudio Cloud\HMT\saml"
$cert1 = Join-Path $path "FortiGate SSL VPN_01.cer"
$cert2 = Join-Path $path "FortiGate SSL VPN_02.cer"
$hash1 = Get-FileHash $cert1 -Algorithm SHA256
$hash2 = Get-FileHash $cert2 -Algorithm SHA256
if ($hash1.Hash -eq $hash2.Hash) {
Write-Output "Los certificados son idénticos (hash SHA256 coincide)."
} else {
Write-Output "Los certificados son diferentes."
Write-Output "Hash1: $($hash1.Hash)"
Write-Output "Hash2: $($hash2.Hash)"
}
A continuación se describe cómo comparar dos archivos de texto que contienen parámetros y valores similares usando Python y PowerShell. El resultado será un archivo HTML con tres columnas: `Parámetro`, `txt1`, y `txt2`.
===== Python =====
El siguiente script en Python compara dos archivos de texto y genera un archivo HTML con las diferencias:
import os
def parse_file(file_path):
parsed_data = {}
with open(file_path, 'r') as file:
section = None
for line in file:
line = line.strip()
if line.startswith("[") and line.endswith("]"):
section = line
elif "=" in line:
key, value = line.split("=", 1)
full_key = f"{section}/{key}" if section else key
parsed_data[full_key] = value
return parsed_data
def generate_html_comparison(file1_data, file2_data, output_file):
keys = sorted(set(file1_data.keys()).union(file2_data.keys()))
with open(output_file, 'w') as html_file:
html_file.write("\n")
html_file.write("| Parámetro | txt1 | txt2 |
\n")
for key in keys:
value1 = file1_data.get(key, "")
value2 = file2_data.get(key, "")
html_file.write(f"| {key} | {value1} | {value2} |
\n")
html_file.write("
")
# Ruta de los archivos de texto
file1_path = "archivo1.txt"
file2_path = "archivo2.txt"
output_file_path = "comparacion.html"
# Parsear los archivos
file1_data = parse_file(file1_path)
file2_data = parse_file(file2_path)
# Generar el HTML de comparación
generate_html_comparison(file1_data, file2_data, output_file_path)
print(f"Comparación completada. Archivo HTML generado: {os.path.abspath(output_file_path)}")
===== PowerShell =====
Este script en PowerShell logra lo mismo que el anterior:
function Parse-File {
param ($FilePath)
$parsedData = @{}
$section = ""
Get-Content $FilePath | ForEach-Object {
$_ = $_.Trim()
if ($_ -match "^\[.*\]$") {
$section = $_
} elseif ($_ -match "=") {
$key, $value = $_ -split "=", 2
$fullKey = if ($section) { "$section/$key" } else { $key }
$parsedData[$fullKey] = $value
}
}
return $parsedData
}
$file1_path = "archivo1.txt"
$file2_path = "archivo2.txt"
$output_file_path = "comparacion.html"
$file1_data = Parse-File $file1_path
$file2_data = Parse-File $file2_path
$keys = ($file1_data.Keys + $file2_data.Keys) | Sort-Object -Unique
$sb = New-Object Text.StringBuilder
$sb.AppendLine("") | Out-Null
$sb.AppendLine("| Parámetro | txt1 | txt2 |
") | Out-Null
foreach ($key in $keys) {
$value1 = $file1_data[$key] -join ","
$value2 = $file2_data[$key] -join ","
$sb.AppendLine("| $key | $value1 | $value2 |
") | Out-Null
}
$sb.AppendLine("
") | Out-Null
$sb.ToString() | Out-File $output_file_path
Write-Output "Comparación completada. Archivo HTML generado: $output_file_path"
==== Explicación ====
- **Parsear los archivos:** Ambos scripts leen los archivos de texto y los dividen en secciones (si existen) y parámetros.
- **Comparar y generar HTML:** Los scripts comparan las claves (parámetros) y crean una tabla HTML donde se muestran los valores de cada archivo en columnas separadas. Si una clave está en un solo archivo, el valor del otro archivo será vacío.
==== Resultado ====
{{:comparaciontxt.png?nolink|}}