Run command prompt as Administrator

2020-01-24 05:28发布

I am developing a small shutdown scheduler project in which i have to put the computer in "Stand By" mode. The command that i am using is

Runtime.getRuntime().exec("cmd /c Powrprof.dll,SetSuspendState ");

This command requires Admin rights which i don't know how to get. Also while searching for previous answers i found i can use elevate.exe as

Runtime.getRuntime().exec("c:/elevate Rundll32.exe Powrprof.dll,SetSuspendState ");

Elevate.exe is doing the task but is consuming too much of time i.e. making the software slow. Is there any other speedy way? I am using Netbeans IDE.

4条回答
冷血范
2楼-- · 2020-01-24 05:51
  Runtime.getRuntime().exec("runas /profile /user:Administrator \"cmd.exe /c Powrprof.dll,SetSuspendState\"");

Also plz see comments

Running as admin without Admin rights

查看更多
唯我独甜
3楼-- · 2020-01-24 05:54

Add parameter /savecred

runas /profile /user:Administrator /savecred

Input the password one times. In future OS will not ask you password.

查看更多
爷的心禁止访问
4楼-- · 2020-01-24 06:07

You have a few options

A. Create a shortcut with admin priv.

The shortcut will run cmd /c Rundll32.exe Powrprof.dll,SetSuspendState

Your Java code will run the shortcut:

Runtime rt = Runtime.getRuntime();
rt.exec("cmd /c start \"\" \"myshortcut.lnk\"")

Right click the shortcut icon > properties > advanced > run as administrator

B. Run the java process as administrator

Again, create a shortcut and set to run as administrator. Any processes spawned will also have admin privileges. Your java code will run:

rt.exec("cmd /c Powrprof.dll,SetSuspendState")

C. Use JNA to directly call SetSuspendState routine. The Java process will require admin priv (like B), but you won't have to spawn a process. If you like this, I can provide source code.

D. Use wizmo utility: wizmo quiet standby

查看更多
欢心
5楼-- · 2020-01-24 06:09

I'm using Windows 10. IDK why but runas isn't working and isn't reporting any errors.

I found this answer on superuser.com:

    powershell -Command "Start-Process 'cmd.exe /c Powrprof.dll,SetSuspendState ' -Verb runAs"
  • No password required if you have permission to elevate.
  • No shortcut required on client machine
  • No dependency on runas
  • Requires powershell

Powershell is installed by default on Windows since Windows 8 and Windows Server 2008 R2, according to an answer found on serverfault.com.

查看更多
登录 后发表回答