创建readonly只读用户脚本

身为一名运维工作人员,保证服务器的安全是必要项,当开发人员或测试人员需登录到服务器查看日志等操作时,可只给定特定的权限防止误操作的惨况产生。
以下脚本内容均为我本人环境,如有更改可自行修改。
~]# vim create_readonly.sh
#!/bin/bash
# 打印脚本使用方法
echo -e "method of application
create_readonly.sh username."
# 将用户输入的第一个参数赋给username这个变量
username=$1
# 将用户家目录赋予home这个变量
home="/home/${username}"
# 判断用户是否存在,如果存在,则退出脚本
id $username &> /dev/null
if [ $? == 0 ];then
   echo User already exists
   exit 2
fi
# 判断用户是否在脚本名后跟了用户名
if [ "x"$username == x"" ]
then
   echo -e "Please enter the user name you want to create.
Usage:'create_readonly.sh username.'"
   exit 2
else
# 创建用户并指定shell环境,成功提示"创建成功"反之提示"创建失败"
   useradd -s /bin/bash $username && echo "The ${username} creating a successful." || "Create a failure."
# 免交互创建用户密码
   echo Abcd1234 | passwd --stdin $username &> /dev/null
# 创建readonly用户可用命令存放目录,给.bin目录赋权,调整.bash_profile文件属主为root,将.bash_profile文件给予700权限且取消编辑功能
   mkdir $home/.bin && chmod 755 $home/.bin && chown root. $home/.bash_profile && chmod 755 $home/.bash_profile && chattr -i $home/.bash_profile
# 将原本.bash_profile中的PATH变量注释,在注释PATH下一行增加"PATH=$HOME/.bin"
   sed -i 's/^PATH/#PATH/' ${home}/.bash_profile
   sed -i '/^#PATH/aPATH=$HOME/.bin' ${home}/.bash_profile
# 后台切换至readonly用户且执行source命令使.bash_profile生效
   su - $username -c "source '$home'/.bash_profile"
# 将允许使用的命令链接至用户家目录中的存放命令位置
   ln -s /usr/bin/tail $home/.bin/tail
   ln -s /usr/bin/cat $home/.bin/cat
   ln -s /usr/bin/top $home/.bin/top
# 修改sshd_config允许readonly用户直接登录至服务器并重启
   sed -i 's/^AllowUsers*/AllowUsers '${username}'/' /etc/ssh/sshd_config
   systemctl restart sshd
# 判断chmod_log.sh文件是否存在
   if [ ! -f "/root/crontab/chmod_log.sh" ]
   then
''' (注释文档)
    如果不存在则创建存放目录及将以下内容重定向至/root/crontab/chmod_log.sh,并赋予执行权限,随及添加计划任务
    #!/bin/bash(内容根据实际情况自行更改)
    chmod -R 755 /mnt/logs/iottest/*/iot*
    chmod -R 644 /mnt/logs/iottest/*/*.log
    chmod -R 644 /mnt/logs/iottest/*/*/*.log*
计划任务:
    每分钟执行一次/root/crontab/chmod_log.sh脚本,保证readonly一直有访问日志的权限
''' (注释文档)
     mkdir /root/crontab
     echo -e '#!/bin/bash
chmod -R 755 /mnt/logs/iottest/*/iot*
chmod -R 644 /mnt/logs/iottest/*/*.log
chmod -R 644 /mnt/logs/iottest/*/*/*.log*' > /root/crontab/chmod_log.sh
     chmod +x /root/crontab/chmod_log.sh
     echo "*/1 * * * * sh /root/crontab/chmod_log.sh  >> /root/crontab/logfile 2>&1" >> /var/spool/cron/root
# 如果文件存在则直接赋予执行权限并添加计划任务
   else
     chmod +x /root/crontab/chmod_log.sh
     echo "*/1 * * * * sh /root/crontab/chmod_log.sh  >> /root/crontab/logfile 2>&1" >> /var/spool/cron/root
   fi
fi

  

原文地址:https://www.cnblogs.com/k-free-bolg/p/11776821.html