在 shell(或类似的)中执行几个提升的命令 [英] Execute several elevated commands in shell (or similar)

查看:36
本文介绍了在 shell(或类似的)中执行几个提升的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以提升的权限执行多个命令,例如:

I have a requirement to execute several commands with elevated rights, something like:

  1. 调用修改服务 .config 文件的程序(需要管理员权限)
  2. net stop myservice(需要管理员权限)
  3. net start myservice(需要管理员权限)

所有这些动态,例如.G.第一行可能包含代理设置,包括用户名和密码,或对设置文件的任何其他修改.(设置文件在程序文件夹中,修改设置文件的程序是外部提供的.实际信息将由用户通过 GUI 输入.)

All of this dynamic, e. g. the first line could contain proxy settings, including user name and password, or any other modification to the settings file. (Settings file is in program folder, program to modify the settings file is externally provided. The actual info would be user entered through a GUI.)

我想创建一个非常灵活的解决方案,使用带有重定向标准输入和标准输出的 cmd.exe 进程.但是..它看起来像runas"(需要ShellExecute)和重定向的输入/输出是独占的.

I thought to create a very flexible solution, using a cmd.exe process with redirected stdin and stdout. But.. it looks like "runas" (needs ShellExecute) and redirected in-/output are exclusive.

(另外,我注意到重定向和 cmd.exe 很难处理.我必须编写自己的函数,例如作为 ReadLine 的替代品,因为 ReadLine 在末尾需要一个 NewLine 并等待,例如,如果有命令提示符(意味着您在行中有文本,例如 c:\bla>,但没有 NewLine.不过,不知道结果是什么使得编写通用内容变得困难.)

(Also, I noticed that redirection and cmd.exe are quite hard to handle.. I had to write my own functions e. g. as a replacement for ReadLine, since the ReadLine expects a NewLine at the end and waits e. g. if there is a command prompt (meaning you have text in the line like c:\bla> but no NewLine. Still, not knowing what one gets as a result makes writing something generic difficult.)

我能想到的有 3 种选择:

There are 3 alternatives I can think of:

  1. 获取每个命令的 UAC 提示(我不喜欢那样)
  2. 启动一个提升的进程,然后它可以调用它想要的任何东西 -> 需要一个我想避免的额外项目 (.exe),也会使部署变得更加困难(额外文件)
  3. 即时创建一个批处理文件,并提升运行它.我也想避免这种情况,因为该文件中可能存在纯文本密码信息(例如,代理的用户/密码).我至少必须确保始终覆盖其内容,然后将其删除.

如何处理?

推荐答案

我认为您已经诊断出问题,并列举了您的可用选项.在我看来,最好的选择是使用 runas 来创建一个新的提升进程,并让该进程完成工作.

I think you've already diagnosed the issue, and enumerated your available options. To my mind the best option is to use runas to create a new elevated process, and get that process to do the work.

另一个进程不需要是不同的可执行文件,它可以是您现有的以特定命令行参数启动的可执行文件.一旦你有另一个进程运行提升,你当然可以使用 cmd 和重定向的 stdin/stdout 来完成这项工作.但是,为什么要使用 net stop/start 而不是服务 API?并且您可以在不启动单独进程的情况下对 .config 文件进行修改吗?

The other process need not be a different executable it could be your existing executable started with particular command line arguments. Once you have another process running elevated, you can certainly use cmd with redirected stdin/stdout to do the work. However, why use net stop/start rather than the service API? And can you do the .config file modification without starting a separate process?

这篇关于在 shell(或类似的)中执行几个提升的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆