测试一个目录是否可以被给定的 UID 写入? [英] Test if a directory is writable by a given UID?
问题描述
我们可以测试当前进程的uid是否可以写一个目录:
We can test if a directory is writable by the uid of the current process:
if [ -w $directory ] ; then echo 'Eureka!' ; fi
但是谁能建议一种方法来测试目录是否可以被某些other uid 写入?
But can anyone suggest a way to test if a directory is writable by some other uid?
我的场景是我正在管理一个 MySQL 服务器实例,我想临时更改慢查询日志文件的位置.我可以通过执行 MySQL 命令 SET GLOBAL slow_query_log_file='$new_log_filename'
然后禁用 &启用查询日志以使 mysqld
开始使用该文件.
My scenario is that I am administering a MySQL Server instance, and I want to change the location of the slow-query log file temporarily. I can do this by executing a MySQL command SET GLOBAL slow_query_log_file='$new_log_filename'
and then disable & enable query logging to make mysqld
start using that file.
但我希望我的脚本检查 mysqld
进程的 uid 是否具有创建新日志文件的权限.所以我想做一些类似(伪代码)的事情:
But I'd like my script to check that the uid of the mysqld
process has permissions to create that new log file. So I'd like to do something like (pseudocode):
$ if [ -w-as-mysql-uid `basename $new_log_filename` ] ; then echo 'Eureka!' ; fi
但这当然是一个虚构的测试谓词.
But of course that's an imaginary test predicate.
澄清:我想要一个不依赖于 su
的解决方案,因为我不能假设我的脚本的用户有 su 权限.
Clarification: I would like a solution that doesn't rely on su
because I can't assume the user of my script has su privilege.
推荐答案
这是一个漫长而迂回的检查方式.
Here's a long, roundabout way of checking.
USER=johndoe
DIR=/path/to/somewhere
# Use -L to get information about the target of a symlink,
# not the link itself, as pointed out in the comments
INFO=( $(stat -L -c "%a %G %U" "$DIR") )
PERM=${INFO[0]}
GROUP=${INFO[1]}
OWNER=${INFO[2]}
ACCESS=no
if (( ($PERM & 0002) != 0 )); then
# Everyone has write access
ACCESS=yes
elif (( ($PERM & 0020) != 0 )); then
# Some group has write access.
# Is user in that group?
gs=( $(groups $USER) )
for g in "${gs[@]}"; do
if [[ $GROUP == $g ]]; then
ACCESS=yes
break
fi
done
elif (( ($PERM & 0200) != 0 )); then
# The owner has write access.
# Does the user own the file?
[[ $USER == $OWNER ]] && ACCESS=yes
fi
这篇关于测试一个目录是否可以被给定的 UID 写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!