Wad*_* M. 50 scripting linux debian shell suid
以不同用户身份运行 shell 脚本的好方法是什么?我正在使用 Debian etch,并且我知道我想模拟哪个用户。
如果我手动进行,我会这样做:
su postgres
./backup_db.sh /tmp/test
exit
Run Code Online (Sandbox Code Playgroud)
由于我想自动化该过程,因此我需要一种将 backup_db.sh 作为 postgres 运行的方法(继承环境等)
谢谢!
bau*_*art 82
要将您的脚本作为另一个用户作为一个命令运行,请运行:
/bin/su -c "/path/to/backup_db.sh /tmp/test" - postgres
Breaking it down:
/bin/su : switch user
-c "/path/to..." : command to run
- : option to su, make it a login session (source profile for the user)
postgres : user to become
Run Code Online (Sandbox Code Playgroud)
我建议总是在这样的脚本中使用完整路径 - 你不能总是保证你在 su 时会在正确的目录中(也许有人改变了你的 homedir,谁知道)。我也总是使用 su (/bin/su) 的完整路径,因为我很偏执。有人可能会编辑您的路径并导致您使用受损版本的 su。
Bas*_*l A 27
如果要运行的目标用户定义了 nologin shelll,则可以使用 -s 选项指定 shell:
/bin/su -s /bin/bash -c '/path/to/your/script' testuser
Run Code Online (Sandbox Code Playgroud)
请参阅以下问题: 以具有 nologin shell 的用户身份运行脚本
Kyl*_*ndt 10
要按计划自动执行此操作,您可以将其放在用户的 crontab 中。尽管 Cron 作业不会获得完整的环境,但最好还是将您需要的所有 env 变量放在脚本本身中。
编辑用户的 crontab:
sudo crontab -u postgres -e
Run Code Online (Sandbox Code Playgroud)