Reputation: 33
I created a program which needs administrator privileges to be executed (in this program I am using a port which is <1024).
So I use this command to execute:
sudo java -jar example.jar
In my program I try to create a folder in this path:
Paths.get("/home/" + System.getProperty("user.name"))
The problem is that System.getProperty("user.name") answers with "root" and so my new directory is in "/home/root/", but I want it in "/home/my_username".
My question is: how can I discover my username and then create the new folder in the right path?
Upvotes: 3
Views: 797
Reputation: 12635
Linux user name is normally bound to the USER
environment variable at login(1)
time. The best approach is to use this variable, as other means (running who(1)
or id(1)
command for example) all do inspect it (using the uid
as parameter, to scan files for it). The same applies for HOME
and SHELL
variables. All of these are collected by login(1)
on authenticating the user (or by the PAM libraries) and get propagated to all derived processes through the environment.
The weird fact is that you can have several usernames bound to the same uid
, and not using the environment can lead you to getting the wrong answer (if you scan the /etc/passwd
file with your uid
as argument, you can get to a different passwd(5)
file entry ---of course, with the same did
) Use:
String username = System.getEnv("USER");
for it.
On other side, if you have created a new session (with sudo(1)
command or similar) and switched both uid
and euid
and the environment has been changed (reinitialised), how you distinguish this from a proper login made by root
account. In that case there are no traces that the process were invoked by a non-root user.
Upvotes: 0
Reputation: 533432
If you do
sudo whoami
it responds with
root
however if I do
sudo bash -c 'echo $SUDO_USER'
I get
peter
You do this from Java with
String user = System.getenv("SUDO_USER");
if (user == null)
user = System.getProperty("user.name");
Upvotes: 2
Reputation: 201399
You can change from
Paths.get("/home/" + System.getProperty("user.name"))
to the user.home
System Property like
Paths.get(System.getProperty("user.home"))
Upvotes: 3