c# - 如何在单击按钮时请求 SecureString 密码以传递给 Power Shell 进程
问题描述
我有一个通过 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)时如何运行此操作。我觉得我几乎什么都懂,但我错过了一些非常重要的东西。
解决方案
感谢所有的建议。
通过使用“Get-Credential”启动 Power Shell 脚本,我能够绕过所有这些,这将提示用户输入密码。更容易(也更安全)。
推荐阅读
- c# - 从工作簿中获取 excel 工作表并将其作为电子邮件附件发送
- c# - 在非 Form 的类上接收和读出 KeyEventArgs 事件
- python - 如何将精灵从矩形更改为图像?
- android - DJI CrystalSky - Toast 消息不显示(间歇性)
- dart - Flutter 中的状态管理(Screen)--> Persist Screen
- java - 如何从序列化对象转换为 POJO
- image - 渲染图像时出现 Flutter 运行时错误
- linux - 按同一行中引用的次数对文本中的单词进行排序
- node.js - Mongoose 身份验证错误:命令查找需要身份验证。但我做到了
- python - 遍历 JSON 列表时丢失一半的记录