linux是多用户系统,root用户具有最高权限,只有root用户才能创建和删除用户(useradd fxc and userdel fxc),其他用户无此权限。
普通用户之间可以使用su随意进行切换(无需输入密码),但是普通用户向root用户切换时,需要输入root的登陆密码
以下介绍在Ubuntu 18.04系统下创建新用户/目录、修改用户权限及删除用户的正确方法。在Ubuntu系统上创建新用户使用[sudo useradd 用户名]命令,但只能创建用户,不能在/home/中创建用户目录,也无法设置用户权限。以下为创建新用户并且分配权限的正确方法。
创建用户(含用户目录)
可以先参考:useradd命令_Linux useradd命令使用详解:
--创建新用户
sudo useradd -r -m -s /bin/bash postgres
--更改密码
sudo passwd postgres
--查看用户家目录
root@ubuntu:~# ls -l /home/
total 8
drwxr-xr-x 4 dhh dhh 4096 Jan 18 12:54 dhh
drwxr-xr-x 2 postgres postgres 4096 Jan 19 18:09 postgres
root@ubuntu:~# ls -l /home/postgres/
total 0
参数说明:
-r:建立系统账号
-m:自动建立用户的登入目录
-s:指定用户登入后所使用的shell
注:
在Ubuntu18.04系统中,不会在创建用户的时候自动提示设置密码。需要手动执行:sudo passwd postgres命令来设置新用户的密码。
修改用户权限
这里采用修改Ubuntu 18.04系统/etc/sudoers文件的方法分配用户权限。因为此文件只有r权限,在改动前需要增加w权限,改动后,再去掉w权限。
--/etc/sudoers文件增加w权限
sudo chmod +w /etc/sudoers
--备份/etc/sudoers文件
cp /etc/sudoers /etc/sudoers_bak_`date +%F`
--更改/etc/sudoers文件
root ALL=(ALL:ALL) ALL下添加postgres ALL=(ALL:ALL) ALL
添加前:
sudo vim /etc/sudoers
# User privilege specification
root ALL=(ALL:ALL) ALL
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL
# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL
# See sudoers(5) for more information on "#include" directives:
#includedir /etc/sudoers.d
添加后:
Defaults env_reset
Defaults mail_badpass
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
# Host alias specification
# User alias specification
# Cmnd alias specification
# User privilege specification
root ALL=(ALL:ALL) ALL
postgres ALL=(ALL:ALL) ALL
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL
# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL
# See sudoers(5) for more information on "#include" directives:
#includedir /etc/sudoers.d
--去掉/etc/sudoers文件的w权限
sudo chmod -w /etc/sudoers
--登录postgres用户并执行权限
root@ubuntu:~# su - postgres
postgres@ubuntu:~$ exit
logout
root@ubuntu:~# su - postgres
postgres@ubuntu:~$ sudo chmod -w /etc/sudoers
[sudo] password for postgres:
至此,新用户创建成功,并且用户目录被创建,权限也分配成功
删除用户
如果要删除用户,请按下面操作进行,分为3步:
--执行userdel命令
sudo userdel postgres
--删除用户目录
sudo rm -rf /home/postgres
--删除用户权限相关配置
(删除或者注释掉/etc/sudoers中关于要删除用户的配置,否则无法再次创建同名用户。)
sudo chmod +w /etc/sudoers #赋予/etc/sudoers文件w权限
vi /etc/sudoers
注释或者删除postgres ALL=(ALL:ALL) ALL #注释或者删除
sudo chmod -w /etc/sudoers #去除/etc/sudoers文件w权限
问题处理
删除用户报错
问题描述
root@ubuntu:~# sudo userdel postgres
userdel: user postgres is currently used by process 4198
问题原因
可能的原因是你创建用户user1之后,使用su命令切换到user1用户下,之后又想删除user1用户,使用su root切换到root用户下,使用userdel user1。出现上述情况的根本原因在于切换回root用户之后,user1还被某个进程占用。
解决办法
ctrl+d(退出当前用户)
第一次使用ctrl+d退出root用户,回到user1用户;第二次使用ctrl+d退出user1用户,此时会返回到root用户(再按ctrl+d退出登陆连接),此时使用userdel user1正常删除。
root@ubuntu:~# sudo userdel postgres
参考链接:userdel: user xxx is currently used by process xxx 解决方案_user is currently used by-CSDN博客