【问题标题】:root running cron task can't read .txt file generated by www-data userroot 运行 cron 任务无法读取 www-data 用户生成的 .txt 文件
【发布时间】:2013-09-16 19:11:58
【问题描述】:

我有一个简单的 php 页面,可以将文件写入我的服务器。

// open new file
     $filename = "$name.txt";
    $fh = fopen($filename, "w");
    fwrite($fh, "$name".";"."$abbreviation".";"."$uid".";");
    fclose($fh);

然后我有一个 cron 作业,我知道它以 root 身份运行并需要它。

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

cronjob是一个bash脚本,可以检测文件是否存在,但是好像不能读取文件的内容。

#!/bin/bash


######################################################
#### Loop through the files and generate coincode ####
######################################################
for file in /home/test/customcoincode/queue/*
    do
    echo $file
    chmod 777 $file
    echo "read file"

    while read -r coinfile; do
      echo $coinfile
    echo "Assign variables from file"

#############################################
#### Set the variables to from the file #####
#############################################

    coinName=$(echo $coinfile | cut -f1 -d\;)
    coinNameAbreviation=$(echo $coinfile | cut -f2 -d\;)
    UId=$(echo $coinfile | cut -f3 -d\;)

    done < $file

    echo "`date +%H:%M:%S` - $coinName : Your Kryptocoin is being compiled!"

    echo $file

    echo "copy $coinName file to generated directory"

    cp -b $file /home/test/customcoincode/generatedCoins/$coinName.txt

    echo "`date +%H:%M:%S` : Delete queue file"

#   rm -f $file



done

echo $file 识别文件存在

echo $coinfile 为空白

然而,当我在终端中nano ./coinfile.txt 时,我可以清楚地看到那里有文字

我运行ls -l,我看到文件有权限

-rw-r--r-- 1 www-data www-data

我的印象是这仍然意味着其他用户可以读取该文件? 如果我打开文件并读取内容,是否需要能够执行该文件?

任何建议将不胜感激。如果你愿意,我可以展开并显示我的代码,但是在我调用 bash 脚本来编写文件之前它是有效的……那时它会在 root 用户下使用 rwx 保存文件,然后可以读取。但这又导致了 php 页面中的其他问题,因此不是一个选项。

【问题讨论】:

  • 非常感谢您的反对和不评论!
  • 我没有投反对票,但您需要发布更多信息以便人们能够帮助您。因为这个问题是无法回答的。请发布您的 bash 脚本的内容、crontab、文件的完整路径以及您得到的 exact 错误。
  • 嘿,感谢您的建设性 cmets :) 我已添加代码以显示正在发生的事情的基础知识。没有错误消息,只是文件被读取为空。完整路径 /home/test/customcoincode/queue/coinfile.txt
  • 你的脚本中#!/bin/bash 前面是否真的有空格,还是复制粘贴错误?
  • 如果您在while 循环的顶部之前立即添加wc $file,您会得到什么输出?

标签: linux bash cron root


【解决方案1】:

你有:

 while read -r coinfile; do
 ...

我没有看到任何迹象表明您正在阅读来自$file 的内容。命令

read -r coinfile

只会从标准输入读取(-r 只会影响反斜杠的处理)。在 cron 作业中,如果我没记错的话,标准输入是空的或不可用,这可以解释为什么 $coinfile 是空的。

如果你确实读过$file——例如,如果你的真实代码看起来像这样:

while read -r coinfile; do
    ...
done <$file

那么您需要向我们展示您的整个脚本,或者至少是显示问题的独立版本。实际上,无论是否存在问题,您都需要向我们展示您的整个脚本。

http://sscce.org/

【讨论】:

  • 好的,我已经包含了我将读取问题隔离到的整个测试 bash 脚本。非常感谢您的回复...我觉得您可能希望我添加更多内容
猜你喜欢
  • 2021-11-28
  • 1970-01-01
  • 2016-06-13
  • 2017-07-31
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多