简体   繁体   English

如何在 linux 或 unix 上找到用户的主目录?

[英]How to find a user's home directory on linux or unix?

How do I find the home directory of an arbitrary user from within Grails?我如何从 Grails 中找到任意用户的主目录? On Linux it's often /home/user.在 Linux 上,它通常是 /home/user。 However, on some OS's, like OpenSolaris for example, the path is /export/home/user.但是,在某些操作系统上,例如 OpenSolaris,路径是 /export/home/user。

Normally you use the statement通常你使用语句

String userHome = System.getProperty( "user.home" );

to get the home directory of the user on any platform.在任何平台上获取用户的主目录。 See the method documentation for getProperty to see what else you can get.请参阅getProperty的方法文档以了解您还能得到什么。

There may be access problems you might want to avoid by using this workaround (Using a security policy file)您可能希望通过使用解决方法来避免访问问题(使用安全策略文件)

For UNIX-Like systems you might want to execute " echo ~username " using the shell (so use Runtime.exec() to run {"/bin/sh", "-c", "echo ~username"} ).对于类 UNIX 系统,您可能希望使用 shell 执行“ echo ~username ”(因此使用Runtime.exec()来运行{"/bin/sh", "-c", "echo ~username"} )。

Try this on Java:在 Java 上试试这个:

System.out.println("OS: " + System.getProperty("os.name") + ", USER DIRECTORY: " + System.getProperty("user.home"));

For an arbitrary user, as the webserver:对于任意用户,作为网络服务器:

private String getUserHome(String userName) throws IOException{
    return new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(new String[]{"sh", "-c", "echo ~" + userName}).getInputStream())).readLine();
}

If your are trying to do this for a user name that you cannot hard code, it can be challenging.如果您尝试为无法硬编码的用户名执行此操作,则可能具有挑战性。 Sure echo ~rbronosky would tell you the path to my home dir /home/rbronosky , but what if rbronosky is in a variable?当然echo ~rbronosky会告诉你我的主目录/home/rbronosky的路径,但是如果 rbronosky 在变量中怎么办? If you do name=rbronosky; echo ~$name如果你这样做name=rbronosky; echo ~$name name=rbronosky; echo ~$name you get ~rbronosky name=rbronosky; echo ~$name你得到~rbronosky

Here is a real world case and the solution:这是一个真实的案例和解决方案:

You have a script that the user has to run via sudo .您有一个用户必须通过sudo运行的脚本。 The script has to access the user's home folder.该脚本必须访问用户的主文件夹。 You can't reference ~/.ssh or else it will expand to /root/.ssh .您不能引用~/.ssh否则它会扩展到/root/.ssh Instead you do:相反,你这样做:

# Up near the top of your script add
export HOME=$(bash <<< "echo ~${SUDO_USER:-}")
# Then you can use $HOME like you would expect
cat rsa_key.pub >> $HOME/.ssh/authorized_keys

The beauty of it is that if the script is not run as sudo then $SUDO_USER is empty, so it's basically the same thing as doing "echo ~".它的美妙之处在于,如果脚本不作为sudo运行,则 $SUDO_USER 为空,因此它与执行“echo ~”基本相同。 It still works as you' expect.它仍然像您期望的那样工作。

If you use set -o nounset , which you should be using , the variable reference ${SUDO_USER:-} will default to blank, where $SUDO_USER or ${SUDO_USER} would give an error (because it is unset) if not run via sudo .如果您使用set -o nounset ,您应该使用它,变量引用${SUDO_USER:-}将默认为空白,如果不通过运行$SUDO_USER${SUDO_USER}将给出错误(因为它未设置) sudo

You can use the environment variable $HOME for that.您可以为此使用环境变量$HOME

If you want to find a specific user's home directory, I don't believe you can do it directly.如果你想找到特定用户的主目录,我不相信你可以直接这样做。

When I've needed to do this before from Java I had to write some JNI native code that wrapped the UNIX getpwXXX() family of calls.当我之前需要从 Java 执行此操作时,我不得不编写一些 JNI 本机代码来包装 UNIX getpwXXX()调用系列。

I assume you want to find the home directory of a DIFFERENT user.我假设您想查找不同用户的主目录。 Obviously getting the "user.home" property would be the easiest way to get the current user home directory.显然,获取“user.home”属性是获取当前用户主目录的最简单方法。

To get an arbitrary user home directory, it takes a bit of finesse with the command line:要获取任意用户主目录,需要对命令行进行一些技巧:

String[] command = {"/bin/sh", "-c", "echo ~root"}; //substitute desired username
Process outsideProcess = rt.exec(command);
outsideProcess.waitFor();
String tempResult;
StringBuilder sb = new StringBuilder();
while((tempResult = br.readLine()) != null) sb.append(tempResult);
br.close();
return sb.toString().trim();

Now technically, we should have a thread waiting on the stdout and stderr so the buffers don't fill up and lock up the process, but I'd sure hope the buffer could at least hold a single username.现在从技术上讲,我们应该有一个线程在 stdout 和 stderr 上等待,这样缓冲区就不会填满并锁定进程,但我确实希望缓冲区至少可以保存一个用户名。 Also, you might want to check the result to see if it starts with ~root (or whatever username you used) just to make sure the user does exist and it evaluated correctly.此外,您可能想检查结果以查看它是否以 ~root (或您使用的任何用户名)开头,只是为了确保用户确实存在并且评估正确。

Hope that helps.希望有所帮助。 Vote for this answer if it does as I'm new to contributing to SO and could use the points.如果我刚开始为 SO 做贡献并且可以使用这些积分,请投票支持这个答案。

eval echo ~$SUDO_USER评估回声〜$ SUDO_USER

might work.可能有效。

To find the home directory for user FOO on a UNIX-ish system, use ~FOO .要在 UNIX-ish 系统上查找用户 FOO 的主目录,请使用~FOO For the current user, use ~ .对于当前用户,使用~

Can you parse /etc/passwd?你能解析 /etc/passwd 吗?

eg:例如:

 cat /etc/passwd | awk -F: '{printf "User %s Home %s\n",  $1, $6}'

Find a Java wrapper for getpwuid/getpwnam(3) functions, they ask the system for user information by uid or by login name and you get back all info including the default home directory.getpwuid/getpwnam(3)函数找到一个 Java 包装器,它们通过 uid 或登录名向系统询问用户信息,你会得到包括默认主目录在内的所有信息。

The userdir prefix (eg, '/home' or '/export/home') could be a configuration item. userdir 前缀(例如,'/home' 或'/export/home')可以是一个配置项。 Then the app can append the arbitrary user name to that path.然后应用程序可以将任意用户名附加到该路径。

Caveat: This doesn't intelligently interact with the OS, so you'd be out of luck if it were a Windows system with userdirs on different drives, or on Unix with a home dir layout like /home/f/foo, /home/b/bar.警告:这不会与操作系统进行智能交互,所以如果它是在不同驱动器上具有 userdirs 的 Windows 系统,或者在具有 /home/f/foo、/home 等主目录布局的 Unix 系统上,您就会倒霉/b/酒吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM