compute engine startup script can't execute as a non-root user

限于喜欢 提交于 2020-04-10 08:36:07

问题


Boiling my issue down to the simplest case, I'm using Compute Engine with the following startup-script:

#! /bin/bash
sudo useradd -m drupal
su drupal
cd /home/drupal
touch test.txt

I can confirm the drupal user exists after this command, so does the test file. However I expect the owner of the test file to be 'drupal' (hence the su). However, when I use this as a startup script I can still confirm ROOT is the owner of the file:

meaning my

su drupal

did not work. sudo su drupal also does not make any difference. I'm using Google Container OS, but same happens on a Debian 8 image.


回答1:


sudo su is not a command run within a shell -- it starts a new shell.

That new shell is no longer running your script, and the old shell that is running the script waits for the new one to exit before it continues.

The sudo su command will start a new shell. The old shell waits for the old one to exit and continues executing the rest of the code. Your script is running in the 'old' shell, which means these commands:

cd /home/drupal
touch test.txt

are still executed as root and thus the owner of these files is root as well.

You can modify your script to this:

#! /bin/bash
sudo useradd -m drupal
sudo -u drupal bash -c 'cd ~/; touch text2.txt'

and it should work. The -u flag executes the command as the user specified, in this case 'drupal'




回答2:


I wrote some stuff underneath - but looks like this should work: how to run script as another user without password

The other option would be to ssh into your own machine as the other user, you can use sshpass to send the password, or get your own public key.

When I test a similar script:

su [my username]
touch test.txt

It actually logs in as me, and doesn't finish until I ctrl-d

Further testing reveals that the only way to own the file is if I invoke the script from the shell, ie:

su me
touch test.txt
./test2.sh

test2.sh: touch test2.txt

gives both files to root, even if I own both scripts. This follows that everything YOU do is yours, you can't make something for someone else.



来源:https://stackoverflow.com/questions/43900350/compute-engine-startup-script-cant-execute-as-a-non-root-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!