How do I disable login of user?

I think that your confusion stems from the fact you don't understand what ! does.

Encrypted passwords are stored in /etc/shadow. For example, after creating a new user named new-user and giving it 12345678 password we get this entry:

$ sudo cat /etc/shadow
(...)
new-user:$6$zVbJcpZE$Bqnxr5cDkwjKOE06iAZu7/qIuH9UGXex28TU/aD0osft9DfdPVzcVwq2j410YxoPlZR310.heZyxaQq4iwWy9.:18038:0:99999:7:::

You can now switch to new-user by doing su new-user and typing 12345678 as the password. You can disable a password for new-user by prepending it with ! like that:

$ sudo cat /etc/shadow
(...)
new-user:!$6$zVbJcpZE$Bqnxr5cDkwjKOE06iAZu7/qIuH9UGXex28TU/aD0osft9DfdPVzcVwq2j410YxoPlZR310.heZyxaQq4iwWy9.:18038:0:99999:7:::

From now on you will not be able to switch to new-user even after providing the correct password:

$ su new-user
Password:
su: Authentication failure

Notice though that modifying /etc/shadow manually is very dangerous and not recommended. You can achieve the same with sudo passwd -l new-user. As man passwd says:

   -l, --lock
       Lock the password of the named account. This option
       disables a password by changing it to a value which matches
       no possible encrypted value (it adds a ´!´ at the beginning
       of the password).

For example:

$ sudo passwd -l new-user
passwd: password expiry information changed.

However, notice that passwd -l does not disable the account, it only disables password and that means that user can still log in the system using other methods as man passwd explains:

       Note that this does not disable the account. The user may
       still be able to login using another authentication token
       (e.g. an SSH key). To disable the account, administrators
       should use usermod --expiredate 1 (this set the account's
       expire date to Jan 2, 1970).

       Users with a locked password are not allowed to change
       their password.

Tags:

Ubuntu