There’s more to a user account than a username. Learn how to set and change all metadata associated with a Linux user account from the command line.
What’s in a name?
If you are using a Linux or Unix-like computer, you will have a user account. The name given to the account is the name of your account. This is the name you use to log in. It is also (by default) the name of your login group and the name of your home directory. They all use the same identifier.
There is another set of information that can be stored for each user account. For example, real data can be assigned to them, such as, for example, the full name of a person, his office number and his work phone number. Indeed, completely arbitrary pieces of information can be tied to user accounts.
In practice, this will be more useful for system administrators who monitor computers that have many user accounts configured. But even for a single-user Linux computer, it’s always interesting to know what’s going on under the hood.
GECOS field
At one time, the Unix pioneers did not have their own printer. They had to move their print jobs to a General Electric mainframe running the General Electric General Electric Operating System (GECOS). To do this, users on Unix systems needed to store and use account credentials on the GECOS system.
The GECOS field was created to store these credentials. This very niche requirement is long gone and the GECOS field has been changed to store other data associated with the owner of the user account. He may have a new job, but he keeps his old name. This is still called the GECOS field.
The field is stored in /etc/passwd along with other user account information:
Account username.
User ID.
Group ID.
Path to the home directory for the user account.
The shell that is launched when the user logs in.
Here the finger command and the pinky command get the information they display.
RELATED:How to use the finger command in Linux
Team ChFN
chfn (change finger information) allows you to set and change the information stored in the GECOS field. The information is stored as a comma-separated list inside the field.
Team chfn was already present in Ubuntu 18.04.1 and Manjaro 18.1.0. It needed to be installed on Fedora 31. Use this command to install it:
sudo dnf установить util-linux-user
Let’s see what finger can find out about the owner of the user account «dave». To get as much information as possible, we will use the option -l (long format):
палец Дэйв-л
Here’s what he could find:
It retrieves the account username, home directory, and default shell. All this is related to the record user. They do not refer to the real person who uses this account. We can use the command chfn to store information about a real person.
Chfn Dave
Usage chfn thus starts a short interactive process. You will be prompted to enter a data value for each piece of information that the GECOS field can contain. The current value for each data value is displayed in brackets []. If you want to save the current data, you can press the «Enter» key and the value in brackets will be saved.
The information we entered was:
Room number : 512
Work phone : 555-4567
Home phone : 555-5432
Let’s check that finger picks up this new information:
палец Дэйв-л
Yes. But you may have noticed that he didn’t suggest changing the full name. This will only be done if you use sudo . But we don’t have to go through the whole session again chfn just because we forgot to use sudo . We can change any data value individually.
Change individual data values
We can set the full name for the user account owner using the option -f (full name) along with sudo .
sudo chfn -f "Дэйв Маккей" Дэйв
And if we check again with finger :
We see that the full name has been added.
There are other options for changing the room number, home phone, and work phone. To change the room (office) number, use the parameter -r (room number):
sudo chfn -r 633 dave
Note that on some distributions you can use the option -o (cabinet number) instead of option -r . More on this soon. Now to see your version options chfn use:
человек ЧФН
To change the office phone number, use the option -w (work phone):
sudo chfn -w 555-1122 Дэйв
Finally, to change your home phone number, use the option -h (home phone number):
sudo chfn -h 555-6576 Дэйв
Let’s use again finger to see if all these changes have been accepted:
палец Дэйв-л
Success. All of these commands worked and the data values were updated.
Using chfn on other user accounts
So much for changing our own information, how about changing GECOS information for other users? It’s just as easy. You must use sudo when you do, but that’s the only difference. Let’s check what data is set for mary’s user account:
палец Мэри-л
The default information is set for this user account. Let’s add to the information:
судо чфн мэри
We will run the same session as before and we will be prompted to enter a data value for each piece of information that can be stored. And since we used sudo we are asked to provide the full name of the data.
Wait, what’s that last item called «Other»?
it is not supported by all versions chfn and you will only see it if you use sudo so we didn’t see it before when we (intentionally) didn’t use sudo With:
Chfn Dave
The «Other» value can contain anything. It has no prescribed or expected use.
Versions chfn that support the «Other» field also provide the option -o (other) to change this value directly. Due to conflict between -o for «office number» and -o for «other», some systems use -r for «room number».
We can see the data stored for user mary’s account in /etc/paswd using less :
меньше / etc / passwd
On systems that support this (check the man page for your version chfn ), you can set the «other» field directly using the option -o (other):
sudo chfn -o "HTG Freelancer" Дэйв
And we can check the details for the dave user account using the command less :
Это поднимает очевидный вопрос. Если ваша версия chfn не поддерживает поле «Другое», как вы можете изменить его? Мы можем сделать это с usermod команды usermod .
Команда usermod
Команда usermod позволяет изменять аспекты учетной записи пользователя с помощью таких действий, как добавление или удаление учетной записи пользователя из групп и изменение оболочки по умолчанию. Он также может быть использован для прямого манипулирования полем GECOS.
Давайте подробнее рассмотрим строку в /etc/passwd для учетной записи пользователя mary. Мы будем использовать grep, чтобы выделить эту строку для нас . Это будет работать, потому что имена пользователей должны быть уникальными. Может быть только одна учетная запись пользователя с именем Мэри.
grep mary / etc / passwd
Отображаются поля в etc/passwd . В качестве разделителя полей используется двоеточие « : ». поля слева направо:
Имя пользователя учетной записи.
«X», обозначающий пароль для этой учетной записи пользователя, хранится в зашифрованном виде в /etc/shadow .
Идентификатор пользователя для учетной записи пользователя mary.
Идентификатор группы для учетной записи пользователя mary.
Поле GECOS.
Путь к домашнему каталогу для учетной записи пользователя mary.
Оболочка, запускаемая при входе владельца учетной записи mary.
Запятая «,» используется в качестве разделителя для значений данных в поле GECOS. Значения в поле GECOS слева направо:
ФИО.
Номер (или кабинет) номер.
Рабочий телефонный номер.
Домашний телефон.
Дополнительная информация.
Обратите внимание, что команда usermod устанавливает для всего поля GECOS новое значение, которое вы usermod . Если все, что вы предоставляете, это полное имя человека, тогда единственное, что в поле GECOS, будет полное имя. Это означает, что вы должны предоставить любые существующие значения данных, которые вы хотите сохранить.
Вот пример. Пользователь Мария получил повышение, и она собирается перейти на четвертый этаж. У нее новый офисный номер, новый рабочий телефон, и мы добавим ее второе имя. Значение ее поля «Другое» также будет меняться. Хотя номер ее домашнего телефона не изменится, мы должны usermod его в строке для usermod .
Нам нужно использовать опцию -c (comment) и нам нужно запустить команду с помощью sudo .
sudo usermod -c "Мэри Кэрол Куинн, 405,5559654,555-7704, Linux Advocate" Мэри
Использование grep для отчета о содержимом файла /etc/passwd для mary показывает, что были добавлены новые значения.
grep mary / etc / passwd
СВЯЗАННЫЕ:Добавить пользователя в группу (или вторую группу) в Linux
Все меняется, ничего не остается
Неточные данные ничего не стоят. Когда информация о людях меняется — офис перемещается, имена меняются, названия ролей — вы можете легко обновить их метаданные, чтобы отразить текущее положение.