Start Command Prompt (CMD) from java as Administrator

牧云@^-^@ 提交于 2019-12-11 12:23:34

问题


I am working on a java project. This project need admin privileges to execute some process in the system. For this is there any way to give admin privileges while starting the project? Is there any way to start command prompt with admin privileges from java?


回答1:


Disclaimer: I assume you are asking this specifically for the Windows platform

There are two ways I'd recommend:

Use the runas program

This is the easiest way and since you actually want a console window the password prompt doesn't look awkward. On the other hand a user might find it suspicious to enter his password into a console window.

Use the CreateProcessWithLogonW API function

This requires you to use a Win32 Java library. (I'd recommend JNA). It is a little more work but it might lead to a better user experience because of the standard Windows login dialog.




回答2:


You can't simply request admin-privileges and you can't start an admin-command-line from an application that was not launched with admin-privileges. This would be a serious security problem.

Instead, you can check if your app was started with administrative privileges and if not prompt the user to do so (showing a little How-To on how to archive this).

Unfortunately this seams to be a bigger problem since there is no standardized way to do this covering all platforms. However this thread gives some ideas: Detect if Java application was run as a Windows admin



来源:https://stackoverflow.com/questions/7832736/start-command-prompt-cmd-from-java-as-administrator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!