提升模式
这里是如何做到这一点。最简单的方法是使用ShellExecute
以elevaded(管理员)权限重新启动可执行文件。
随着Ruby中,你做这样的:
require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute('path_to_ruby_program', nil, nil, 'runas')
如果你启用了Windows UAC这会给你熟悉的Windows弹出对话框,请求管理员权限。一旦你点击是,你的进程将以管理员权限运行。
这里的秘密技巧是使用未公开的ShellExecute
操作参数runas
,这将提升请求的操作。
http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx
还涉及如何手动创建一个提升的命令提示符快捷方式(这可能是在某些情况下,一个足够好的解决方案)的讨论:
http://www.sevenforums.com/tutorials/3718-elevated-command-prompt-shortcut.html
另一种方法是,以确保您不要以非管理员模式运行你的脚本。我发现这个解决方案在我的经验中是令人满意的。
它可以脚本是否在管理员模式下运行,像这样被确定 -
def running_in_admin_mode?
query_admin_mode_cmd = 'reg query "HKU\S-1-5-19"'
output, exit_status = execute_command(query_admin_mode_cmd)
exit_status == 0
end
幸得彼得·麦克沃伊他的回答here
我要感谢卡斯帕和thegreendroid此修改解。
我无法让他们的例子运行,所以通过触摸更多的研究,我把它放在一起。我做了一些搜索execute_command
,因为我安装的ruby 1.9.3不知道如何处理它,我找不到任何东西,所以我用反引号。 \
必须逃脱。该2>&1
位是如此ruby实际上得到输出,而不是一个空白字符串,如果该输出匹配正则表达式/ERROR/
那么你没有管理员权限,所以我们希望它返回nil
。
这将重新启动自己的管理权限,然后加载任何你放在require
与后面的评论。
require 'win32ole'
def running_in_admin_mode?
(`reg query HKU\\S-1-5-19 2>&1` =~ /ERROR/).nil?
end
if running_in_admin_mode?
require './main.rb' # load the actual program here.
else
path = 'rubyw.exe ' + File.expand_path(__FILE__) # optionally 'ruby.exe '
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute(path, nil, nil, 'runas')
end
你可以放下def
块,改变if
声明
if (`reg query HKU\\S-1-5-19 2>&1` =~ /ERROR/).nil?
为简洁起见。你也可以失去shell
变量:
WIN32OLE.new('Shell.Application').ShellExecute(path, nil, nil, 'runas')
可能的疑难杂症:如果running_in_admin_mode?
反复失败,这可以无限循环,但它完美地为我工作。
'ShellExecute'语法应该是: 'shell.ShellExecute(“rubyw.exe”,path,“”,'runas')' 更多信息可以在这里找到:http://rubyonwindows.blogspot.com.es/ 2007/05 /启动,应用程序和打印,文档,with.html –
由于其他作者,我来这个工作(在Windows 8测试):
在Ruby脚本的顶部添加此:
def running_in_admin_mode?
(`reg query HKU\\S-1-5-19 2>&1` =~ /ERROR/).nil?
end
unless running_in_admin_mode?
require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute("ruby", File.expand_path(__FILE__), nil, 'runas')
exit
end
# admin rights ensured
do_something()
或者您也可以有含
cd full\path
ruby myscript.rb
和launcher.cmd推出具有管理员权限此CMD文件
Ø你已经用红宝石测试过,你可以试试rubyw
用管理员权限打开终端(cmd.exe)并从那里运行ruby? – Casper
是的,这是一种提升任何事情的方式不是吗?我需要一种脚本红宝石升级的方式。很明显,Windows会要求输入管理员密码,这对我来说可以。 –