Linux usermod change shell

how to change the default shell of an user in linux?

There are several different command shells available to you in Linux. bash, csh, tcsh, ksh, zsh, sh and fish are just a few of the popular ones that can be used by an user from the command line. As a system administrator, you can specify a default shell for the user. The user can however choose the run another shell of his choice later by overriding the default shell.

For this post, we will assume that your current default shell is csh and you want to change it to bash. The steps will however work just the same for any shell that you want to change to.

First thing to do is to make sure that you have the required shell installed, in this case the bash shell. You need to find the path to the shell executable or where the shell is installed. The shells are usually installed in the /bin/ folder unless you have a distro which installs in other locations such /usr/bin/ or /usr/local/bin/.

find location of the shell

You can find where the shell is installed by using either which or whereis command. The which command will show you exactly where in the path the shell executable is.

If which cannot find the shell you want to change to, and you are sure that it is installed then you might want to double check the environment path and make sure that the installed folder is in the path. The location of the shell executable is all you need to change the default shell.

Unlike the which command, the whereis command will show you the location of the binary/executable, source and documentation of the command. The first path in the output is the location of the shell binary.

You can see the list all the shells that are installed on your system in the /etc/shells file. Use the cat command to print out the contents of this file. It lists the binary file location of the installed shells. You can change to any of the shell listed here.

change the default shell

Once you have the location of the new shell, you can change the default for any user as long as you have the root or super user credentials. You can use either the usermod or the chsh command to do it. You can also do it manually by editing the passwd file.

$ usermod -s /bin/bash

usermod is the command used to modify user accounts. The -s or –shell option is used specify the default shell for the user. Substitute in the above example with the actual username of the user.

Another command you can use is chsh. It changes the login shell or the default command shell for any user. The syntax of this command is just about the same as the usermod command above.

The -s or –shell option is for the path of the new shell followed by the actual username for the user.

You can also change the shell directly in the /etc/passwd file. This is probably more riskier than using the commands above. The default shell of the user is the last field on the line where the user is listed. Use your favorite text editor to open the /etc/passwd file and search and find the user name in the file. You will see something like this :

Читайте также:  Disable hyper v in the windows host

Now change the “/bin/csh” part of the line to “/bin/bash” and save the file. The modified line will look like this:

change shell at time of use

If you do not have root access or the permission to modify the /etc/passwd file, then you are left with the option of executing the shell after you have logged in. This does not change the default shell but still allows you use the shell of your choice.

First, you need to find the location of the shell as described above. Now, find the file that configures your current shell. You will see that there are several files that fits, such as .profile, .bashrc, .bash_profile, .login etc etc. The differences between these files are beyond the scope of this post.

I recommend that you use the rc file, for example .bashrc or .cshrc. The reason for using it is that it is read by the interactive, login and non-login prompts. You can use any of the configuration files depending on your requirements.

So, if your default shell is csh then open the .cshrc file in your favorite text editor and add the following to it…

setenv SHELL /bin/bash
exec /bin/bash —login

If your current default shell is something other than csh, then you will use the corresponding file. You can just use the .login or .profile as well, which are usually read by most shells. Be sure to use the correct syntax for setting the environment variable SHELL for the shell.

Also, you will need to add any personalization and shell specific configuration in the config file of the new executing shell. That means you can set aliases and prompt format etc in the .bashrc file once you have changed to the bash shell.

Источник

3 Ways to Change a Users Default Shell in Linux

In this article, we will describe how to change a user’s shell in Linux. The shell is a program that accepts and interprets commands; there are several shells such as bash, sh, ksh, zsh, fish and many other lesser known shells available on Linux.

Bash (/bin/bash) is a popular shell on most if not all Linux systems, and it’s normally the default shell for user accounts.

There are several reasons for changing a user’s shell in Linux including the following:

  1. To block or disable normal user logins in Linux using a nologin shell.
  2. Use a shell wrapper script or program to login user commands before they are sent to a shell for execution. Here, you specify the shell wrapper as a user’s login shell.
  3. To meet a user’s demands (wants to use a specific shell), especially those with administrative rights.

When creating user accounts with the useradd or adduser utilities, the —shell flag can be used to specify the name of a user’s login shell other than that specified in the respective configuration files.

A login shell can be accessed from a text based interface or via a SSH from remote Linux machine. However, if you login via a graphical user interface (GUI), you can access the shell from a terminal emulators like xterm, konsole and many more.

Let’s first list all available shells on your Linux system, type.

Before you proceed any further, note that:

  • A user can change their own shell to any thing: which, however must be listed in the /etc/shells file.
  • Only root can run a shell not listed in /etc/shells file.
  • If an account has a restricted login shell, then only root can change that user’s shell.

Now let’s discuss three different ways to change Linux user shell.

1. usermod Utility

usermod is a utility for modifying a user’s account details, stored in the /etc/passwd file and the -s or —shell option is used to change the user’s login shell.

In this example, we’ll first check user tecmint’s account information to view his default login shell and then change its login shell from /bin/sh to /bin/bash as follows.

Change User Shell using Usermod

2. chsh Utility

chsh is a command line utility for changing a login shell with the -s or –shell option like this.

Change User Shell Using chsh

The two methods above all modify the shell specified in /etc/passwd file which you can edit manually as in the third method below.

Читайте также:  Ace stream 64 bit для windows

3. Change User Shell in /etc/passwd File

In this method, simply open the /etc/passwd file using any of your favorite command line text editors and change a specific users shell.

Change User Shell in Passwd File

When your done editing, save and close the file.

Do not forget to read these related topics:

In this article, we described various ways of changing a user’s shell in Linux. To share any thoughts with us, use the comment section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How To Change Default Shell In Linux

In most Linux systems, the default shell is bash but we can change that to any other shell-like zsh, fish, sh, and any other. In this article, we are going to show how to change that default shell to any other shell in Linux systems. To change the user’s shell, first, let’s find the current shell. There are many ways by which we can change the shell of any user on a Linux system. We are going to see three methods of changing the user’s shell.

Find your current shell name

In Linux systems, there is one file which is /etc/passwd. The /etc/passwd file stores essential information of user accounts, which is required during login. By using this file we can identify the current user login shell.

We are going to see the current user information in the /etc/file using the following command:

In the above image we can see that the user nishant (current user) has home directory /home/nishant and the shell is /bin/sh

List your shells in Linux

Now to change the shell, first, we need to see which shells are installed on the system. We can check installed shells using the following command :

This will show all shells as follows:

Before moving further, first understand who can change the user shell

  • Users can change shell to any other shell listed in /etc/shells/.
  • The root account can be used to change any other user login shell.
  • If an account has a restricted login shell, then only the root can change that user’s shell.

Changing default sh shell to bash

Using usermod command

usermod is a command that modifies the system account files. usemod can change the shell of Users by modifying file /etc/passwd. usermod command provides the -s or –shell option to change the user’s login shell.

In this example, we are going to change the shell of a user named nishant. We are going to change the shell from /bin/sh to /bin/bash of user nishant using usermod command.

With usermod command mention shell and usernmae after –shell option.

Now you can see the shell use changed. In the above commands, replace nishant with the user name whose shell has to change.

Using chsh Utility

chsh is the utility to change a user’s login shell. chsh provides the -s option to change the user’s shell. This method also modifies the file /etc/passwd. Use the following command to change shells using chsh:

Change User Shell to /etc/passwd File

As we see in the above two methods, the usermod command and chsh utility modify the /etc/passwd file and change the user shell. We can do that manually also by editing the /etc/passwd file. Just change the shell after the username and home directory in the /etc/passwd file and save the file.

Источник

Команда Usermod в Linux

usermod — это утилита командной строки, которая позволяет изменять данные для входа пользователя.

В этой статье рассказывается, как использовать команду usermod для добавления пользователя в группу, изменения оболочки пользователя, имени входа, домашнего каталога и т. Д.

Команда usermod

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

Читайте также:  What is happening with windows phone

Только root или пользователи с доступом sudo могут вызывать usermod и изменять учетную запись пользователя. В случае успеха команда не выводит никаких результатов.

Добавить пользователя в группу

Наиболее типичный вариант использования usermod — добавление пользователя в группу.

Чтобы добавить существующего пользователя во вторичную группу, используйте параметры -a -G после имени группы и имени пользователя:

Если вы хотите добавить пользователя к нескольким группам одновременно, указать группы после того , как -G опция разделяться , (запятыми) без промежуточных пробелов.

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

Всегда используйте параметр -a (добавить) при добавлении пользователя в новую группу. Если вы опустите опцию -a , пользователь будет удален из групп, не перечисленных после опции -G .

Если пользователя или группы не существует, команда предупредит вас.

Изменить основную группу пользователя

Чтобы изменить основную группу пользователя, вызовите команду usermod с параметром -g следующим за именем группы и именем пользователя:

В следующем примере мы меняем основную группу пользователя linuxize на developers :

Каждый пользователь может принадлежать ровно к одной основной группе и нулю или более вторичных групп.

Изменение информации о пользователе

Чтобы изменить информацию GECOS (полное имя пользователя), запустите команду с параметром -c за которым следует новый комментарий и имя пользователя:

Вот пример, показывающий, как добавить дополнительную информацию пользователю linuxize:

Эта информация хранится в /etc/passwd .

Изменение домашнего каталога пользователя

В большинстве систем Linux домашние каталоги пользователей названы по имени пользователя и создаются в каталоге /home .

Если по какой-то причине вы хотите изменить домашний каталог пользователя, вызовите команду usermod с параметром -d usermod абсолютный путь к новому домашнему каталогу и имя пользователя:

По умолчанию команда не перемещает содержимое домашнего каталога пользователя в новый. Чтобы переместить содержимое, используйте параметр -m . Если новый каталог еще не существует, он создается:

Вот пример, показывающий, как изменить домашний каталог пользовательских www-data на /var/www :

Изменение пользовательской оболочки по умолчанию

Оболочка по умолчанию — это оболочка, которая запускается после входа в систему. По умолчанию в большинстве систем Linux в качестве оболочки по умолчанию используется Bash Shell.

Чтобы изменить оболочку пользователя по умолчанию, запустите команду с параметром -s указав абсолютный путь оболочки и имя пользователя:

В приведенном ниже примере мы меняем оболочку пользователя на Zsh:

Вы можете узнать, какие оболочки доступны в вашей системе, просмотрев содержимое файла /etc/shells .

Изменение UID пользователя

UID (идентификатор пользователя) — это номер, присвоенный каждому пользователю. Он используется операционной системой для обозначения пользователя.

Чтобы изменить UID пользователя, вызовите команду с параметром -u следующим за новым UID и именем пользователя:

В приведенном ниже примере показано, как изменить номер «UID» на «1050»:

UID файлов, принадлежащих пользователю и находящихся в домашнем каталоге пользователя, и файл почтового ящика пользователя будет изменен автоматически. Право собственности на все остальные файлы необходимо изменить вручную.

Изменение имени пользователя

Хотя не очень часто, иногда вам может потребоваться изменить имя существующего пользователя. Параметр -l используется для изменения имени пользователя:

В приведенном ниже примере мы переименовываем пользователя linuxize в lisa в «1050»:

При изменении имени пользователя вы также можете изменить домашний каталог пользователя, чтобы отразить новое имя пользователя.

Установка даты истечения срока действия пользователя

Дата истечения срока — это дата, когда учетная запись пользователя будет отключена. Чтобы установить дату истечения срока действия пользователя, используйте параметр -e :

Срок годности должен быть установлен в формате YYYY-MM-DD .

Например, чтобы отключить пользователя linuxize 21 2022-02-21 , вы должны выполнить следующую команду:

Чтобы отключить истечение срока действия учетной записи, установите пустую дату истечения срока действия:

Используйте команду chage -l для просмотра даты истечения срока действия пользователя:

Дата истечения срока хранения хранится в /etc/shadow .

Блокировка и разблокировка учетной записи пользователя

Параметр -L позволяет заблокировать учетную запись пользователя:

Команды вставят восклицательный знак ( ! ) Перед зашифрованным паролем. Если поле пароля в /etc/shadow содержит восклицательный знак, пользователь не сможет войти в систему, используя аутентификацию по паролю. Другие методы входа в систему, такие как аутентификация на основе ключей или переключение на пользователя , по-прежнему разрешены. Если вы хотите заблокировать учетную запись и отключить все методы входа в систему, вам также необходимо установить дату истечения срока действия равной 1.

В следующих примерах показано, как заблокировать пользователя linuxize :

Чтобы разблокировать пользователя, запустите usermod с параметром -U :

Выводы

Мы показали вам, как использовать команду usermod для установки информации об учетной записи пользователя.

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

Источник

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