file-folder-helper/ADO2024/PI2/Helper-2024-07-28.cs
2024-10-11 09:15:32 -07:00

64 lines
2.6 KiB
C#

using Microsoft.Extensions.Logging;
using System.Diagnostics;
namespace File_Folder_Helper.ADO2024.PI2;
internal static partial class Helper20240728
{
internal static void DownloadSslCertificates(ILogger<Worker> logger, List<string> args)
{
string file;
Process? process;
string[] segments;
string standardError;
string standardOutput;
string argumentSegment;
string store = args[9];
string domain = args[2];
List<string> lines = [];
string logSegment = args[8];
string endCertificate = args[7];
string beginCertificate = args[6];
int waitForExit = int.Parse(args[5]);
string[] subdomains = args[3].Split(',');
string sourceDirectory = Path.GetFullPath(args[0]);
ProcessStartInfo processStartInfo = new()
{
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
FileName = args[4],
WorkingDirectory = sourceDirectory
};
foreach (string subdomain in subdomains)
{
argumentSegment = $"{subdomain}.{domain}:443 -servername {subdomain}.{domain}";
processStartInfo.Arguments = $"s_client -connect {subdomain}.{domain}:443 -servername {subdomain}.{domain}";
process = Process.Start(processStartInfo);
if (process is null)
continue;
_ = process.WaitForExit(waitForExit);
process.Kill(entireProcessTree: true);
standardOutput = process.StandardOutput.ReadToEnd();
if (!standardOutput.Contains(beginCertificate) || !standardOutput.Contains(endCertificate))
{
standardError = process.StandardError.ReadToEnd();
logger.LogWarning($"Error: {subdomain}{Environment.NewLine}{standardOutput}{Environment.NewLine}{standardError}");
continue;
}
segments = standardOutput.Split(beginCertificate);
if (segments.Length != 2)
break;
segments = segments[1].Split(endCertificate);
if (segments.Length != 2)
break;
lines.Add($"{logSegment} \"{store}\" {subdomain}.{domain}.cert");
file = Path.Combine(sourceDirectory, $"{subdomain}.{domain}.cert");
File.WriteAllText(file, $"{beginCertificate}{segments[0]}{endCertificate}{Environment.NewLine}");
}
File.WriteAllLines(Path.Combine(sourceDirectory, $"{DateTime.Now.Ticks}.txt"), lines);
}
}