Files
HP_InHand_IG502/VPN/extract_creds.py
2025-02-20 17:11:50 -06:00

52 lines
1.7 KiB
Python

import os
import re
import argparse
def extract_and_save(ovpn_path):
"""Extracts certificates/keys from an .ovpn file and saves them as separate files in the same directory."""
# Check if file exists
if not os.path.isfile(ovpn_path):
print(f"Error: File '{ovpn_path}' not found.")
return
# Define regex patterns for extracting sections
sections = {
"ca": r"<ca>(.*?)</ca>",
"cert": r"<cert>(.*?)</cert>",
"key": r"<key>(.*?)</key>",
"tls-auth": r"<tls-auth>(.*?)</tls-auth>"
}
# Read the .ovpn file
with open(ovpn_path, "r", encoding="utf-8") as file:
data = file.read()
# Get directory of the .ovpn file
output_dir = os.path.dirname(ovpn_path) or "."
# Loop through sections and extract data
for name, pattern in sections.items():
match = re.search(pattern, data, re.DOTALL)
if match:
content = match.group(1).strip()
filename = f"{name.replace('-', '_')}.crt" if name in ["ca", "cert"] else f"{name.replace('-', '_')}.key"
file_path = os.path.join(output_dir, filename)
with open(file_path, "w", encoding="utf-8") as f:
#f.write(f"-----BEGIN {name.upper()}-----\n")
f.write(content + "\n")
#f.write(f"-----END {name.upper()}-----\n")
print(f"Extracted: {file_path}")
print("Extraction complete!")
# Command-line argument handling
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Extract certificates and keys from an OpenVPN .ovpn file.")
parser.add_argument("ovpn_file", help="Path to the OpenVPN .ovpn configuration file")
args = parser.parse_args()
extract_and_save(args.ovpn_file)