Open the file with admin privilege in ruby - ruby

On windows machine(with Windows 7 running, x86-64) is it possible to open 'etc/hosts' file which is in system32/drivers/etc, modify it and save from ruby?
I get "not opened for writing(IOError)" error
The code is very simple
file = File.open("C:/Windows/System32/drivers/etc/hosts")
file << "new line"

Instead of trying to acquire privileges from code ( which maybe won't be portable across different windows OS'es ), do like this:
open a command prompt as an administrator
run your script from there
By doing like this, all the programs you're executing will have administrative privileges as well.
EDIT: This is your problem:
file = File.open("C:/Windows/System32/drivers/etc/hosts","w")
file << "new line"
You have to open the file in write mode.

My best work around is have ruby open an elevated command prompt when necessary. It will prompt the user for a password, but it is better than nothing.
username = `whoami`.chomp
run = "runas /noprofile /user:#{username} \"cmd /C #{cmd}\""
system(run)
cmd can be any command that you want to run with permissions. What I do to edit a host file is:
hosts_path = 'C:\windows\System32\drivers\etc\hosts'
hosts_file = File.open(host_path,'r') {|f| f.read}
...
--edit the hosts_file here--
...
cmd = "echo \"#{hosts_file}\" > #{hosts_path}"

Related

Double-Click Execute as Administrator

I have a powershell file saved to my desktop that I'd like to be able to double-click on and run as administrator. I've tried updating the shortcut used to launch powershell to always run as admin, but I still get the same permission issue. Is there a way to setup the shortcut so that the file always executes as admin? Or another way to set it up so that all powershell scripts run as admin when double-clicked?
Thanks for any help!
Create a "proxy script" to launch other scripts as admin with, and then launch PowerShell using Start-Process -Verb RunAs to elevate it before execution:
RunAsProxy.ps1
# First arg should be the script path
$script = $args[0]
# Rest of args should be any script parameters
$scriptArgs = $args[1..$args.Count] -join ' '
$startProcessArgs = #{
Wait = $true
Verb = 'RunAs'
FilePath = 'powershell'
ArgumentList = "-File `"$script`" $scriptArgs"
}
Start-Process #startProcessArgs
exit $LASTEXITCODE
Create your shortcut to point to RunAsProxy.ps1 instead of the target script. Pass in the path to the target script you want to run elevated and optionally any parameters to that script. If UAC is enabled, you should get prompted to elevate before execution.
This should be re-usable with other scripts you want to do the same with.

How to invisibly execute a privilege command in VBScript with a normal user

Today I do e.g.:
Set WshShell = CreateObject("WScript.Shell")
Call WshShell.Run("psexec -u administrator -p pw1234 cmd /c netsh interface ip show address > C:\Output.txt", 2, True)
This works, but the command prompt window is always visible for a short time.
I've been searching the web and I've tried everything I could possibly think of to hide/minimize this window, but unfortunately without success.
So I'm afraid that there's no way to run psexec in a hidden/minimized window.
But is there perhaps another way to execute a privilege command in VBScript with a normal user where no command prompt window is visible?

Windows script opening cmd and running a command

So i'm trying to write a script which checks if the cmd is with administrative privileges. If it is I just ran the command - which is a jar file. If it isn't what I did was create a link to the cmd and in that link I made it always run as administrator.
The problem is that after it runs the command it opens the second cmd as administrator but then the command needs to be written again. Is there any chance to save the command written and as the second cmd opens run it?
net session >nul
if %errorLevel% == 0 (
java -jar %~dp0/myjar.jar%*
) else (
echo Administrative permissions required
cmdadmin.lnk
)
cmdadmin.lnk is as I said a link to cmd which in the advanced properties I set as run as administrator.
Now what I want is to pass a command when opening the link. Is it possible?

Windows: Batch File: Only Run as Administrator

I have a batch file to start an application as a Windows service. It is called start.bat
#ECHO off
START c:\Ruby193\bin\ruby c:\Ruby193\bin\thin start -R c:\coolapp\config.ru -p 4321 -a localhost -e production
My challenge is that this program only runs properly if it is "Run as Administrator" with admin privileges. So, I would like to add a line to check if this script is actually run with administrative privileges, and only execute if it is being run as administrator.
How can I do that from within the script?
Something like this might be what you need:
set isadmin=0
whoami /all | findstr /c:" S-1-16-12288 ">nul && set isadmin=1
That should result in the %isadmin% variable being either 1 or 0 depending on whether the shell was run as administrator or not.
This assumes the existance of the whoami utility which won't necessarily be available on older versions of Windows - I believe it was included from Windows Vista onwards though.
Two options:
Provoke elevation from a WSH script, like documented in the blog post Scripting Elevation on Vista.
Use an external executable that provokes the UAC prompt, such as Elevate32.exe/Elevate64.exe.
For your scenario, #2 may be preferable because you can detect whether the elevation prompt was canceled (exit code 1223) and you can also wait for the launched executable to finish before continuing (-w parameter).
Bill
It would probably be easier to convert the script to VBScript, then you can more easily check for Admin privileges and even elevate the script to Admin.
See here for how to do the check in VBScript: VBScript: Check if the script has administrative permissions

How to set System EnvVar when UAC is active (Windows Script Host)

I have to create a script which updates a system environment variable (based on a command line parameter) before launching a program.
In Windows 7, updating the system environment variable is denied. I would like to perform a privilege elevation for just the setting of the env. var. But run the program as a normal user.
How to do it?
Note:
I've tried the following solution:
Using 2 scripts:
1 master which get all information from command line, which call the slave script to change the system env. var., and which finally launch the program
1 slave script that update the system env. var.
the master script tries to call the slave script using privilege elevation, but that does not work
I've try 2 solutions for the privilage elevation:
Using the "runas /User:Administrator ..." command but it ask for the Administrator password: Fail
Using the "ShellExecute ...., "runas"" command but it tells me that my script is not an application: Fail
I found a way that is working at least on Windows 7 (don't know if it will work on the few Windows XP hat we still have around).
I did the following from the main script:
currentDirectory = left(WScript.ScriptFullName,(Len(WScript.ScriptFullName))-(len(WScript.ScriptName)))
Set UAC = WScript.CreateObject("Shell.Application")
UAC.ShellExecute "wscript.exe", currentDirectory + "my-script.vbs /Param1:Value1 ...", "", "runas", 0
And the my-script is doing the sys var env update.
Note: My fist experience with ShellExecute failed because I was trying to execute the script. Instead of "wscript.exe" I had "my-script.vbs" for the executable name.
IMHO, disable UAC, it's just a pain in the *
But if you can't (like me 8<), you can use
psexec.exe -d -u userid -p password CMD /c program_with_path
You (or the user where the sript runs) will have to confirm the prompt though.

Resources