1

Sorry I didn't clearly mention that I am working with windows, so the solutions related to linux Is there any way to execute a process through another user using java (by giving username and password in the code)?

Currently I am using process p = Runtime.getRuntime().exec("cmd") but I need to run this as a different user. Is there any function that supports this? or any other approach in java?

Edited: Sorry I didn't mention it previously that I am working on windows. So the solutions related to linux os are not applicable.

Jahanzaib
  • 121
  • 2
  • 9
  • I don't know of a way to change who you are, and it sounds pretty security unfriendly. However, you could potentially use that exec to run a paramaterized script that uses su to switch to that user, then performs what you want? – billjamesdev Feb 14 '16 at 04:53
  • 1
    [This](http://stackoverflow.com/questions/1012792/running-unix-commands-as-different-user-from-java) thread ( a bit older ) might offer more insights – Alfiyum Feb 14 '16 at 04:58
  • Yes this is a good thread but I am looking for a way in Windows, actually when I use runas command, it asks for the user password, I need to do that through java code in jar file. so that it automatically uses runas and inserts the password at the back end. – Jahanzaib Feb 19 '16 at 06:26

1 Answers1

1

You need to call a command that takes care of the "run as other user" functionality. For example "su" or "sudo" on Linux1. This functionality is not availability from the JVM because:

  • it is inherently platform specific, and
  • it would be dangerous to support it in the JVM2.

There is also the issue that if it is risky to write (or use) programs that handle users' passwords on their behalf. Especially for users who don't understand and follow "best practice" in managing their passwords.


1 - ... though "sudo" has a different access control model.

2 - For a start, this functionality requires root privilege and a JVM running with root privilege is a major security risk.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Okay. Thanks. That makes sense but if we ignore the security risks for instance, how can we achieve this functionality of using runas command through java and also inserting the password from the java .jar file? I am working on windows – Jahanzaib Feb 19 '16 at 06:36