Адрес домашней папки linux

How to Find User’s Home Directory in Linux or Unix

Under a Linux operating system distribution environment, a created/existing system user is associated with a Home directory. The configuration of the Home directory ensures that the files belonging to the currently active Linux user are only accessible to that user unless this user switches to another user account where they will access the Home directory of that switched user.

The files under a Linux Home user directory are specific to the currently active users. The base directory of the Linux operating system is the root (/) directory.

It is from the root (/) directory that we should be able to access the Home (/home) directory.

If you only have a single active user on your Linux operating system environment, dealing with the Home directory is straightforward. The latter statement implies that every created/existing Linux user will have their system username as a directory name under this Linux Home directory.

For instance, listing the directories in the above Home directory lists three other directories to imply that the Linux operating system in question hosts 3 three users.

View Linux Home Directory

If we decide to navigate into either of the above Linux user folders, we should first be able to meet the following prerequisite.

It is only by being a sudoer/root user that we can be able to navigate into other Linux users’ Home directories without bumping into permission/access barriers.

View User Home Directory

From the above display, we have managed to navigate to the Home directory and list the files, folders, and directories associated with user dnyce whose user directory exists within the Home (/home) directory.

The above screen capture also reveals to us the different file permissions associated with the listed files, folders, and directories. The file permissions starting with – e.g – rw-rw-r— , imply that we are dealing with a file and the file permissions starting with d e.g drwxr-xr-x , imply that we are dealing with a folder or directory.

Ways to Find User’s Home Directory in Linux

Before we look at some viable approaches to finding a user’s home directory in Linux, it is important to understand why the Home directory exists. This directory helps differentiate system-wide data from user data such that we do not have to deal with redundancy. Also, important file backup operation becomes flawless.

Читайте также:  Linux find command and or

You first need to be sure that the Linux user exists. This approach is a summary of the above-discussed content.

The tilde (~) symbol indicates that we are at the home directory of the currently active user.

Find User Home Directory

The Linux user’s home directory contains directories like Documents, Downloads, Music, Pictures, and Public.

Find User’s Home Directory Using Cd Command

Executing the cd (change directory) command alone should take you to the home directory of the current Linux user.

Find User Home Directory

Another approach is to use cd + tilde (~) should navigate us to the Home directory of the currently logged-in user.

Switch to User Home Directory

You can also use $HOME command, which takes you to the Home directory as a variable.

Not only do we understand the concept of the Linux user’s home directory, but we can navigate to it from any directory path.

Источник

Как узнать домашнюю директорию любого пользователя Linux

Для того, чтобы правильно и безопасно хранить данные на сервере, (особенно, если на этом сервере несколько пользователей), следует точно знать, где располагаются их домашние папки, до которых у пользователей есть доступ (у каждого в свою, но нет доступа в чужие папки с чужими данными). Например, для того, чтобы дать пользователю доступ по ftp только к его данным или подсказать полный путь до его www-директории. В этой статье рассмотрим то, как узнать домашнюю директорию любого пользователя Linux несколькими способами.

Где хранится системная информация о домашних каталогах пользователей в Linux

При создании нового пользователя в Unix-системах, каждому пользователю обязательно домашний каталог. О том, где и как располагается запись о домашней директории пользователя в файле /etc/passwd , подробно описано в → этой статье. Для понимания вопроса сейчас требуется знать, что это предпоследнее (шестое) поле home в строке записи пользователя в этом файле:

login : password : UID : GID : GECOS : home : shell

Поэтому, можно в цикле обходить этот файл в поиске записи нужного пользователя, разбивать строку на подстроки и брать значение 6-го поля. Но это слишком длинный способ. Есть короче и проще. 😉

Команда pwd в Unix

Команда pwd выводит текущий путь к директории, в которой находится пользователь. Выполнив команду pwd , получим этот путь:

У пользователя root в Unix по умолчанию домашней директорией является /root .

Оператор ~ (тильда) в Debian

Другой способ того, как определить домашнюю директорию текущего пользователя. Достаточно посмотреть значение оператора ~ (тильда):

Результат не сильно отличается от предыдущего, но к ~ можно добавлять дополнительные пути к папкам и/или файлам пользователя, используя её как точку отсчёта в домашней директории пользователя. Что сильно облегчает работу с написанием относительных путей (относительно не только корня файловой системы, но и корня домашней папки пользователя).

Читайте также:  Дефолтный пароль kali linux

Ещё одним полезным свойством ~ является то, что с помощью этого оператора можно получить путь до домашней директории любого пользователя в системе (если конечно пользователь есть в системе, то есть прописан в файле /etc/passwd , например посмотреть содержимое домашнего каталога пользователя ftp можно так, поставив перед ним тильду ~ :

А теперь посмотреть содержимое этого файла:

[email protected]:~# cat ~ftp/welcome.msg Welcome, archive user %U@%R ! The local time is: %T This is an experimental FTP server. If you have any unusual problems, please report them via e-mail to .

Ну и то, к чему мы стремились: посмотреть путь к домашней директории пользователя:

Так гораздо удобнее, чем парсить и разбирать файл /etc/passwd . За нас всю эту работу делает операционная система! 😉

Заберите ссылку на статью к себе, чтобы потом легко её найти!
Раз уж досюда дочитали, то может может есть желание рассказать об этом месте своим друзьям, знакомым и просто мимо проходящим?
Не надо себя сдерживать! 😉

Источник

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? On Linux it’s often /home/user. However, on some OS’s, like OpenSolaris for example, the path is /export/home/user.

Can you be a bit more specific? Do you look for the home directory of the user that runs grails, or for the home directory of an arbitrary user whose name or UID you have?

13 Answers 13

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.

There may be access problems you might want to avoid by using this workaround (Using a security policy file)

The app server will run as a production user and be located in /opt, for example. This may, or may not work, depending on how the production account is set up. Therefore, asking for the production user’s home directory might not be the answer.

The OP was asking for the home of an arbitrary user. But user.home is the one of the current user. Is this method always working if you would go from the current users home to the parent and then down to the directory with the specified users name?

For UNIX-Like systems you might want to execute » echo ~username » using the shell (so use Runtime.exec() to run ).

Shelling out an doing an ‘echo ~username’ seems like the neatest answer. I see so many people who type ‘cd /home/username’ instead of ‘cd ~username’ . Of course, you should never shell out, if you don’t have to.

Читайте также:  Arch linux fix boot

But since Java doesn’t provide an API for this, the only alternative I can think of is JNI, which is even worse than calling a shell.

Running echo ~ seems to do the trick if you’re signed in as the user whose home directory you’re looking for.

To be super-precise here — /bin/sh is guaranteed under POSIX to be a Bourne-compliant shell, but tilde expansion ( ~ and ~user ) is not one of the required features of such shell. Linux distributions use BASH as /bin/sh , for which tilde expansion works. If you run echo ~ using /bin/sh under some other UNIX OS, you can get back just the tilde (e.g. «~» ) instead of home directory path.

This does not answer the question. They didn’t ask how to find their own home directory, they asked how to find a user’s home directory.

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[]).getInputStream())).readLine(); > 

You can use the environment variable $HOME for that.

$HOME changes depending on which user is logged in. I don’t see how it can be used to find the home of an arbitrary user.

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.

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.

To get an arbitrary user home directory, it takes a bit of finesse with the command line:

String[] command = ; //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. 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.

Hope that helps. Vote for this answer if it does as I’m new to contributing to SO and could use the points.

Источник

Оцените статью
Adblock
detector