通过shell脚本将用户添加到sudoers [英] Adding users to sudoers through shell script

查看:372
本文介绍了通过shell脚本将用户添加到sudoers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过shell脚本将用户添加到sudoers文件中? 我一直在环顾四周,仍然找不到任何东西.

Is it possible to add users to the sudoers file through a shell script? I've been looking around, still can't find anything.

推荐答案

您可以直接将echo(当然具有提升的特权)直接存储到/etc/sudoers文件中:

You could simply echo (with elevated privileges, of course) directly to the /etc/sudoers file:

sudo -i
echo 'nickw444  ALL=(ALL:ALL) ALL' >> /etc/sudoers
#             ^^
#             tab

(请注意用户名和第一个ALL之间的制表符)

(note the tab character between the username and the first ALL)

或者,对于脚本:

#!/bin/bash
# Run me with superuser privileges
echo 'nickw444  ALL=(ALL:ALL) ALL' >> /etc/sudoers

然后保存到somefile.shchmod a+rx,然后从终端窗口运行sudo ./somefile.sh.

Then save to somefile.sh, chmod a+rx it, and run sudo ./somefile.sh from a terminal window.

要添加多个用户,请将脚本更改为此;

To add multiple users, change the script to this;

#!/bin/bash

while [[ -n $1 ]]; do
    echo "$1    ALL=(ALL:ALL) ALL" >> /etc/sudoers;
    shift # shift all parameters;
done

然后,像这样运行脚本(假设您将其保存为addsudousers.sh):

Then, run the script like this (assuming you saved it as addsudousers.sh):

sudo ./addsudousers.sh bob joe jeff

,即以空格分隔.

要从文件中读取名称,请执行以下操作:

To read the names from a file:

nickw444@laptop ~ $ sudo ./addsudousers.sh `cat listofusers.txt`

listofusers.txt也应以空格分隔.

Jappie Kirk

Jappie Kirk rightly points out that you can't directly call sudo echo ... >> /etc/sudoers because the >> redirection is handled by the shell, which has by that point dropped the superuser privileges. However, if you run a script that contains echo ... >> /etc/sudoers and the script itself has superuser privileges, everything should work just fine.

这篇关于通过shell脚本将用户添加到sudoers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆