Run CMD under different credentials

.NET 2.0 has the ability to specify different user credentials when starting a new process via Process.Start(). The password for the user has to be supplied via the new SecureString class (read more here).

First you have to collect the password in a safe manner from the user. The new Console members are your friend here. We add the characters for the password one at a time via Console.ReadKey to the SecureString, which tucks it away encrypted in a safe store outside of the managed heap. We don’t even echo the password back to the console. cool.

SecureString password = new SecureString();
            
Console.Write(“Enter Password for {0}: “, args[0]);
while (true)
{
  ConsoleKeyInfo cki = Console.ReadKey(true);
  if (cki.Key == ConsoleKey.Enter)
   break;
  else if (cki.Key == ConsoleKey.Escape)
   return;
  else if (cki.Key == ConsoleKey.BackSpace)
  {
   if (password.Length != 0)
    password.RemoveAt(password.Length 1);
  }
  else
   password.AppendChar(cki.KeyChar);
}

after that we simply pass the SecureString to the process’ StartupInfo and we are finished. nice.

ProcessStartInfo si = new ProcessStartInfo();

si.FileName = “cmd.exe”;
si.Arguments = “/k Title *** cmd running as “ + args[0] + ” *** && color 4F && PROMPT=$P$_$+$G”;
si.WorkingDirectory = Environment.CurrentDirectory;
si.UseShellExecute = false;
                
si.UserName = args[0];
si.Password = password;
si.LoadUserProfile = true;
Process.Start(si);

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s