建立readonly只读用户脚本

身为一名运维工做人员,保证服务器的安全是必要项,当开发人员或测试人员需登陆到服务器查看日志等操做时,可只给定特定的权限防止误操做的惨况产生。
如下脚本内容均为我本人环境,若有更改可自行修改。
~]# vim create_readonly.sh
#!/bin/bash
# 打印脚本使用方法
echo -e "method of application\ncreate_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.\nUsage:'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/a\PATH=$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\nchmod -R 755 /mnt/logs/iottest/*/iot*\nchmod -R 644 /mnt/logs/iottest/*/*.log\nchmod -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
相关文章
相关标签/搜索