Linux create directory as different user

Как создавать каталоги в Linux (команда mkdir)

В системах Linux вы можете создавать новые каталоги либо из командной строки, либо с помощью файлового менеджера вашего рабочего стола. Команда, позволяющая создавать каталоги (также известные как папки), — это mkdir .

В этом руководстве рассматриваются основы использования команды mkdir , включая повседневные примеры.

Синтаксис команды Linux mkdir

Синтаксис команды mkdir следующий:

Команда принимает в качестве аргументов одно или несколько имен каталогов.

Как создать новый каталог

Чтобы создать каталог в Linux, передайте имя каталога в качестве аргумента команды mkdir . Например, чтобы создать новый каталог newdir вы должны выполнить следующую команду:

Вы можете убедиться, что каталог был создан, перечислив его содержимое с помощью команды ls :

drwxrwxr-x 2 username username 4096 Jan 20 03:39 newdir 

При указании только имени каталога без полного пути он создается в текущем рабочем каталоге.

Текущий рабочий каталог — это каталог, из которого вы запускаете команды. Чтобы изменить текущий рабочий каталог, используйте команду cd .

Чтобы создать каталог в другом месте, вам необходимо указать абсолютный или относительный путь к файлу родительского каталога. Например, чтобы создать новый каталог в каталоге /tmp вы должны ввести:

Если вы попытаетесь создать каталог в родительском каталоге, в котором у пользователя недостаточно прав, вы получите сообщение об ошибке Permission denied :

mkdir: cannot create directory '/root/newdir': Permission denied 

Параметр -v ( —verbose ) указывает mkdir печатать сообщение для каждого созданного каталога.

Как создать родительские каталоги

Родительский каталог — это каталог, который находится над другим каталогом в дереве каталогов. Чтобы создать родительские каталоги, используйте параметр -p .

Допустим, вы хотите создать каталог /home/linuxize/Music/Rock/Gothic :

mkdir /home/linuxize/Music/Rock/Gothic

Если какой-либо из родительских каталогов не существует, вы получите сообщение об ошибке, как показано ниже:

mkdir: cannot create directory '/home/linuxize/Music/Rock/Gothic': No such file or directory 

Вместо того, чтобы создавать недостающие родительские каталоги один за другим, вызовите команду mkdir с параметром -p :

mkdir -p /home/linuxize/Music/Rock/Gothic

Когда используется опция -p , команда создает каталог, только если он не существует.

Если вы попытаетесь создать каталог, который уже существует, а параметр -p не mkdir , mkdir выведет сообщение об ошибке File exists :

mkdir: cannot create directory 'newdir': File exists 

Как установить разрешения при создании каталога

Чтобы создать каталог с определенными разрешениями, используйте параметр -m ( -mode ). Синтаксис для назначения разрешений такой же, как и для команды chmod .

Читайте также:  Linux уникальное имя файла

В следующем примере мы создаем новый каталог с разрешениями 700 , что означает, что только пользователь, создавший каталог, сможет получить к нему доступ:

Когда опция -m не используется, вновь созданные каталоги обычно имеют права доступа 775 или 755 , в зависимости от значения umask .

Как создать несколько каталогов

Чтобы создать несколько каталогов, укажите имена каталогов в качестве аргументов команды, разделенные пробелом:

Команда mkdir также позволяет создать сложное дерево каталогов с помощью одной команды:

mkdir -p Music/,Classical/Baroque/Early>

Приведенная выше команда создает следующее дерево каталогов :

Music/ |-- Classical | `-- Baroque | `-- Early |-- Disco |-- Folk |-- Jazz | `-- Blues `-- Rock |-- Gothic |-- Progressive `-- Punk 

Выводы

Команда mkdir в Linux используется для создания новых каталогов.

Для получения дополнительной информации о mkdir посетите страницу руководства mkdir .

Если у вас есть вопросы, не стесняйтесь оставлять комментарии ниже.

Источник

Create a file as a different user and group

I have a bash script that has to rsync to download files writing them locally, and then needs to set the owner to apache, and the group to a particular user group (that apache is not a member of). Is there a way to create those files with those ownerships as they’re being written by the rsync process, without having to go through and change them after the fact using chown? There are so many files that the time it takes to go through them later is prohibitive. I have to do this for multiple user groups, so I shouldn’t be adding apache to these groups, and certainly can’t make all of them the default group. In other words: is there a way root can create a file as user X and group Y when X is not a member of Y? I’ve tried using runuser, but I’m unable to set the group (presumably because apache doesn’t belong to the group). I know you can use chmod to change permissions and add any user/group combination. What I’m asking is if there is a way to open a file for writing and use any user/group combo while creating it. Attempt using sudo:

[root@centos7 tmp]# groups angelo angelo : angelo wheel [root@centos7 tmp]# groups apache apache : apache [root@centos7 tmp]# sudo -u angelo -g apache touch angelo-file Sorry, user root is not allowed to execute '/bin/touch angelo-file' as angelo:apache on centos7 [root@centos7 tmp]# ls -ld angelo-file ls: cannot access angelo-file: No such file or directory [root@centos7 tmp]# sudo -u angelo -g angelo touch angelo-file [root@centos7 tmp]# ls -ld angelo-file -rw-r--r-- 1 angelo angelo 0 Nov 12 03:13 angelo-file 

That question is asking about the filesystem. You can chmod the file to give any user/group you want. I want to know if you can open a file descriptor acting as any user/group combo. If it is possible, then I haven’t found out how.

Читайте также:  Ip address linux настройка

I mean using normal Linux tools or commands. I would accept an answer that could verify that you could only do this in C because no tools exist. But I also wouldn’t be surprised if you can’t even do it in C and this is not an available request through the API. sudo with -g will work if the user is a member of the group, but seems to be disallowed if not.

Источник

Shell Programming and Scripting

How to create a directory inside root as different user

Member Information Avatar

157, 25

Bug

How to create a directory inside root as different user

I have directory under /opt/test.
The ownership of the test directory is root:root.

I have login to the server as test user.
I need to have some script to create a directory inside /opt/test.
This script will be called as test user.

When I try to execute this script, I am getting error as Permission denied.

How I can solve this great issue.

Forum Staff

vbe

Member Information Avatar

6,876, 694

The ownership? what about the permissions?

———- Post updated at 16:14 ———- Previous update was at 16:13 ———-

Member Information Avatar

10, 0

vbe is correct to ask for ownership and permissions on /opt/test.

Just a little background, any time you create a new file or directory UNIX/Linux sets the ownership to the user id and group id of the user creating the file. The permissions that vbe mentions are if you can read, write, or execute the file. These are set to a default value that is part of your environment.

Here is a few commands that you might be interested in:

chown — changes the ownership of a file for user id.
chgrp — changes the ownership of a file for group id.

chmod — permission of files.

umask — default permissions for newly created files.

Hope these helps, let me know if I have helped.

Источник

Creating A User with Different Home Directory in Linux

Linux is a powerful multi-user operating system. It can have many concurrent users accessing the system at the same time. The system admin can manage permissions for each user to specify which user can access what part of the system.

This guide will demonstrate how to create a new user with a different home directory in Linux.

User home directory

In Linux, each user gets its own home directory with exceptions like various system accounts. The home directory is a dedicated directory for the particular user to store the user-specific files. It’s also referred to as the “login directory”. Whenever logging in, the user will land on the respective home directory.

Читайте также:  Разрядность linux как узнать

By default, all the users in the system have their home directories located at the following location.

Each home directory is named after the username of the user. For example, the home directory for the user “viktor” will look like this.

However, we can establish a different location for the user directory. It can be set during the creation of the user account or moved later.

Creating a user with a different home directory

Creating a new user

Each Linux system comes with useradd, a dedicated tool to create and update user accounts. It’s only available to the root user and non-root users with sudo privileges.

To add a new user to the system, run the following useradd command. The flag “-m” tells useradd to create a dedicated home directory for the new user. If not used, then the user won’t have a dedicated home directory.

The user is added to the system. The user is also registered to various database files (/etc/passwd, /etc/shadow, /etc/gshadow, and /etc/group).

The user isn’t accessible yet. The following command will assign a login password for the new user.

The user is ready and fully functional. Access the new user.

Check the location of the home directory of the new user.

Creating a user with a custom home directory

By default, useradd will create the user’s home directory under “/home”. To specify the home directory in a different location, use the flag “-d”. Note that the directory must exist beforehand.

As always, use passwd to assign a login password for the new user.

Verify if the new user has a different home directory.

Moving existing user home directory

We can also assign a different home directory for an existing user. It will not move the contents of the existing home directory automatically to the new location.

Create a new directory. It will be the new home directory of an existing user.

Allow the new user complete access over the new directory.

Move all the contents of the existing user home directory to the new one.

Assign the new directory as the home of the user.

Verify the change.

Final thoughts

The home directory is an important part of a normal user account on Linux. This guide demonstrates how to assign a custom home directory to a new and existing user. These methods apply to any Linux distro.

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.

Источник

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