using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace UpdateStoredPwd
{
class Program
{
static void Main(string[] args)
{
Regex reTarget = new Regex("Target: (?<t>.+):target=(?<s>.+)");
Regex reUser = new Regex("User: (?<u>.+)");
Console.Write("User: ");
string account = Console.ReadLine();
Console.Write("Password: ");
Console.ForegroundColor = ConsoleColor.Black;
string pwd = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
bool catchAccount = false;
string currTarget = null, currType = null;
foreach (string line in Execute("cmdkey", "/list")
.Replace("\r", string.Empty).Split('\n'))
{
if (!catchAccount)
{
var m = reTarget.Match(line);
if (m.Success)
{
catchAccount = true;
currTarget = m.Groups["s"].Value;
currType = m.Groups["t"].Value;
}
}
else
{
var m = reUser.Match(line);
if (m.Success)
{
catchAccount = false;
string user = m.Groups["u"].Value;
if (string.Compare(user, account, true) == 0)
{
string a = string.Format(
"/{3}:{0} /user:{1} /pass:{2}", currTarget, account,
pwd, currType == "Domain" ? "add" : "generic");
Console.WriteLine("cmdkey " +
a.Replace("pass:" + pwd, "pass:*****"));
string res = Program.Execute("cmdkey", a);
Console.WriteLine(res);
}
}
}
}
Console.Read();
}
static string Execute(string prog, string args)
{
Process p = new Process();
p.StartInfo = new ProcessStartInfo(prog, args);
//必須要設定以下兩個屬性才可將輸出結果導向
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
//不顯示任何視窗
p.StartInfo.CreateNoWindow = true;
p.Start();
StringBuilder sb = new StringBuilder();
while (!p.HasExited)
{
string line = p.StandardOutput.ReadLine();
sb.AppendLine(line);
}
return sb.ToString();
}
}
}