0

I have found a link that illustrates the use of getting pwd based in the uid of the user.

I have a similar requirement in java for running a script as a different user which needs this implemetation.

The code snippet in c++ is as below:

static void su(const char* user)
{
    struct passwd* pwentry=getpwnam(user);
    if(!pwentry)
        COUT<<"su:getpwnam:couldnot get pwd entry for user %s",user;
    uid_t new_uid=pwentry->pw_uid;
    struct passwd* pwentry_nmsadm=getpwnam("nmsadm");
    if(!pwentry_nmsadm)
        cout<<"su:getpwnam:could not get pwd for nmsadm");
    gid_t new_gid=pwentry->pw_gid;
    if(chdir(pwentry->pw_dir)<0)
        cout<<"su:chdir";
    uid_t current_uid=geteuid();
    gid_t current_gid=getegid();
    if(current_gid!=new_gid)
    {
        if(setgid(new_gid)<0)
        cout<<"su:setgid";
    }
    if(current_uid!=new_uid)
    {
        if(setuid(new_uid)<0)
        cout<<"su: setuid";
    }

Please suggest some links that can be helpful(libraries that can be used) or solution to the above requirement in java.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
Galaxin
  • 474
  • 2
  • 9
  • 21

1 Answers1

1

Java does not provide this out-of-the-box, since it is both system dependant and would break security concepts of Java.

Some possible solutions could be:

  • Use a JNI wrapper to call your C++ method, so that you can do everything you need in C++
  • Use ssh to launch the script as a different user
  • Use sudo to launch the script as a different user

See also

Community
  • 1
  • 1
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • Thanks for the guidance but I cannot use ssh or sudo as i can not pass the pwd into them in order to execute the required operations – Galaxin Apr 09 '13 at 09:19