CentOS使用run-as-user.sh處理執行環境的使用者不同問題
很多時候,部署執行環境的使用者和實際執行的使用者是不同的,
當因為環境限制,當時碰到以下場景的時候,就比較麻煩了,需要編寫一個指令碼來實現執行。
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 $@