【问题标题】:How to request a SecureString password on button click to pass to a Power Shell process如何在单击按钮时请求 SecureString 密码以传递给 Power Shell 进程
【发布时间】:2019-09-09 18:52:52
【问题描述】:

我有一个通过 Power Shell 运行命令的应用程序。我知道如何以不同的用户身份运行它,但我完全不知道如何获取密码。我想每次都提示用户输入密码(我只希望应用程序最多使用一次),所以我不需要存储它。我了解我需要将密码创建为安全字符串。最重要的是,我希望它在单击按钮时运行,但我不知道如何调用它。这是我目前所拥有的:

class Credentials  
{
    private static SecureString MakeSecureString(string text)  
    {  
        SecureString secure = new SecureString();  
        foreach (char c in text)  
        {  
            secure.AppendChar(c);  
        }        

        return secure;
    }

    public static void RunAs(string path, string username, string password)
    {
        try
        {

            Process process = new Process();
            process.StartInfo.FileName = "powershell.exe";
            process.StartInfo.UserName = "adminaccount@account.com";
            process.StartInfo.Password = MakeSecureString(password);
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.UseShellExecute = false;
            process.Start();
            process.StandardInput.WriteLine(" Some Power Shell Script");
            process.StandardInput.Flush();
            process.StandardInput.Close();
            process.WaitForExit();
            Console.WriteLine(process.StandardOutput.ReadToEnd());
            Console.WriteLine(process.StandardError.ReadToEnd());
            Console.Read();
        }
        catch (Win32Exception w32E)
        {
            // The process didn't start.
            Console.WriteLine(w32E);
        }
    }
}

// Later invoked in this button click handler
private void Button_Click(object sender, EventArgs e)
{
    Credentials.SecureString();
    Credentials.RunAs();
}

单击按钮时如何运行此按钮 (Button_Clicked)。我觉得我几乎什么都懂,但我错过了一些非常重要的东西。

【问题讨论】:

  • 您的Credentials 类没有SecureString 方法(Button_Click 中的第一行)。

标签: c# .net powershell passwords


【解决方案1】:

RunAs() 方法的方法签名采用 3 个参数,但在 Button_Clicked 处理程序中,您不向其传递任何参数 - 修复:

private void Button_Click(object sender, EventArgs e)
{
    string path = @"C:\path\to\file";
    string username = "User1";
    string password = "Sup3r5eCr37p@s$w0rd";
    Credentials.RunAs(path, username, password);
}

我想你会想从表单中 UI 元素的文本字段中获取 pathusernamepassword 的值

【讨论】:

    【解决方案2】:

    感谢所有建议。

    通过使用“Get-Credential”启动 Power Shell 脚本,我能够绕过所有这些,这将提示用户输入密码。更容易(也更安全)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多