su & sudo

来源:互联网 发布:消防海湾主机编程实例 编辑:程序博客网 时间:2024/03/29 08:51

1. su: 使用没有参数的su命令将运行一个root用户的交互shell。此时需要提供root用户的密码方可。

     [bitsec@localhost /]$ su
     密码:
     [root@localhost /]# 

     另外一个经常使用的su命令是su - ,其与su的主要区别是用户所在的目录是否进行切换。使用su -将会切换到指定用户的主目录,效果如下:

    [bitsec@localhost ~]$ pwd
    /home/bitsec
    [bitsec@localhost ~]$ su -
    密码:
    上一次登录:日 2月  1 15:22:59 CST 2015pts/0 上
    [root@localhost ~]# pwd
    /root
    [root@localhost ~]# 

     可以看出,此时用户的工作目录已经发生了变化

2. sudo:如果我们切换到root用户后,没有返回普通用户,这时如果我们进行了特权操作,则可能对系统造成不可估量的后果,比如删除了重要的系统文件。因此,如果我们需要使用root用户完成工作之后能自动回到原来的普通用户,可以使用sudo命令。该命令的使用方法是将要执行的命令前面加上sudo即可。如 sudo ls /bin

     但是并不是所有的用户可以使用该命令,如下:

    [bitsec@localhost ~]$ sudo ls /etc
    [sudo] password for bitsec:
    bitsec 不在 sudoers 文件中。此事将被报告。

    虽然我们使用了正确的密码,但是却没有执行相应的命令,而是告诉我们用户没有在sudoers文件中。那sudoers文件是干什么的那?他在那里那?

   在Linux系统中,能使用sudo的用户可以叫做sudoer。添加sudoer的方法有:

  • visduo或者sudoedit:visudo会用vim编辑器打开/etc/sudoers文件让我们修改添加sudoer用户
  • 使用其他编辑器打开/etc/sudoers文件进行修改

    sudoers文件内容如下:

## Sudoers allows particular users to run various commands as
## the root user, without needing the root password.
##
## Examples are provided at the bottom of the file for collections
## of related commands, which can then be delegated out to particular
## users or groups.
##
## This file must be edited with the 'visudo' command.

<--省略部分内容-->


## Next comes the main part: which users can run what software on
## which machines (the sudoers file can be shared between multiple
## systems).
## Syntax:
##
##      user    MACHINE=COMMANDS
##
## The COMMANDS section may have other options added to it.
##
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows members of the 'sys' group to run networking, software,
## service management apps and more.
# %sys ALL = NETWORKING, SOFTWARE, SERVICES, STORAGE, DELEGATING, PROCESSES, LOCATE, DRIVERS

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
# %wheel        ALL=(ALL)       NOPASSWD: ALL

## Allows members of the users group to mount and unmount the
## cdrom as root
# %users  ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom

## Allows members of the users group to shutdown this system
# %users  localhost=/sbin/shutdown -h now

## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d


重要的是红色一行,他说明root用户可以通过任意主机登录并执行所有命令,所以要将一个用户添加到sudo组中,需要在红色行的下面添加下面一行后保存退出(假设想加入sudo组的用户为bitsec):

bitsec ALL=(ALL) ALL

现在再执行sudo命令,效果如下:

[bitsec@localhost ~]$ sudo ls /home
bitsec



0 0
原创粉丝点击