Y at-il un moyen d'obtenir l'UID de l'utilisateur sur la machine Linux en utilisant java?

StackOverflow https://stackoverflow.com/questions/4796172

  •  24-10-2019
  •  | 
  •  

Question

Y at-il un moyen d'obtenir l'UID de l'utilisateur sur la machine Linux en utilisant java? Je suis au courant de la méthode de System.getProperty("user.name");, mais il retourne son nom d'utilisateur et je suis à la recherche d'UID.

Était-ce utile?

La solution

vous pouvez exécuter la commande de id et lire le résultat.

par exemple:

$ id -u jigar

sortie:

1000

vous pouvez exécuter la commande par

try {
    String userName = System.getProperty("user.name");
    String command = "id -u "+userName;
    Process child = Runtime.getRuntime().exec(command);

    // Get the input stream and read from it
    InputStream in = child.getInputStream();
    int c;
    while ((c = in.read()) != -1) {
        process((char)c);
    }
    in.close();
} catch (IOException e) {
}

la source

Autres conseils

Si vous pouvez influencer la façon dont la machine virtuelle Java est démarré, vous pourriez transfert uid comme propriété de l'utilisateur:

java -Duserid=$(id -u) CoolApp

Dans votre coolapp, vous pouvez simplement récupérer l'ID avec:

System.getProperty("userid");

Cordialement,

Martin.

Il suffit d'ouvrir le fichier /etc/passwd et la recherche de la ligne qui a un utilisateur égal à System.getProperty("user.name").

Un autre choix appellerait getuid () en utilisant JNI.

Il est en fait un api pour cela. Il n'y a pas besoin d'appeler une commande shell ou utiliser JNI, juste

def uid = new com.sun.security.auth.module.UnixSystem().getUid()
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top