CentOS使用run-as-user.sh处理运行环境的用户不同问题

栏目: 服务器 · 发布时间: 7年前

很多时候,部署运行环境的用户和实际运行的用户是不同的,

当因为环境限制,当时碰到以下场景的时候,就比较麻烦了,需要编写一个脚本来实现运行。

1.不能使用su和sudo时

2.用户没有 shell 不支持login时,比如nobody,服务用户

3.使用 Docker 等容器时

4.使用SSH远程执行命令,但是不能使用登陆用户

实现前提

1.需要运行用户的用户名和用户分组以及密码

2.需要运行用户的PUID和PGID

使用前请修改代码中实际运行的用户名,且用户存在

./run-as-user.sh 命令 命令参数
#!/bin/sh
 
##############################################################################
# If a PUID/PGID enviroment variable exists, use those values for the `uid`
# and `gid` when executing scripts, otherwise change the dev user's uid and
# gid to match the user that owns the project directory and run a command as
# that user. If a ~/.ssh directory exists and it's not owned by root then
# switch and run as that user instead in order to take advantage of public key
# authentication.
##############################################################################
 
stat_dir="/app"
if [ -d "/home/dev/.ssh" ] && [ "0" != "$(stat -c '%g' /home/dev/.ssh)" ] && [ "0" != "$(stat -c '%u' /home/dev/.ssh)" ]; then
    stat_dir="/home/dev/.ssh"
fi
 
# if the PUID environment variable exists, assume that is the preferred user id,
# otherwise use the $stat_dir
if [ "" != "$PUID" ]; then
    uid=$PUID
else
    uid=$(stat -c '%u' $stat_dir)
fi
 
# if the PGID environment variable exists, assume that is the preferred group id,
# otherwise use the $stat_dir
if [ "" != "$PGID" ]; then
    gid=$PGID
else
    gid=$(stat -c '%g' $stat_dir)
fi
 
# Ensure the correct user id is available in the sudoers file (if the
# specified UID already existed in the image)
id -nu $uid > /dev/null 2>&1
if [ 0 -eq $? ]; then
    echo "$(id -nu $uid) ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers
fi
 
# update the dev user with the specified UID/GID values
groupmod -g $gid -o dev > /dev/null 2>&1
usermod -u $uid -o dev > /dev/null 2>&1
chown -R dev:dev ~dev/ > /dev/null 2>&1
 
# prevent circular calls to this script (legacy support)
cmd="$@"
cmda=`expr "x$cmd" : "x.\{0\}\(.\{0,12\}\)"`
cmdb=`expr "x$cmd" : "x.\{1\}\(.\{1,12\}\)"`
 
while [ "/run-as-user" = "${cmda}" ] || [ "/run-as-user" = "${cmdb}" ]; do
    shift
    cmd="$@"
done
 
sudo -u dev $@

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

腾讯之道

腾讯之道

艾永亮、刘官华、梁璐 / 机械工业出版社 / 2016-7-19 / 59

放眼整个中国乃至全球,腾讯都是一家成功的互联网企业,它代表中国企业在世界互联网版图中竖起了一面高高的旗帜。腾讯为何能取得如此大的成就,它的成功方法和商业逻辑是什么?你是不是和无数中国企业和商界人士一样,都想向腾讯取取经,但是又不得其门而入? 腾讯一直以低调、务实著称,所 以腾讯及其内部员工都极少对外界分享他们的经验;加之腾讯的商业模式多元、业务繁多且交叉、体量又极其庞大,使得从外部来系统研究......一起来看看 《腾讯之道》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

html转js在线工具
html转js在线工具

html转js在线工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具