我在 cronjob 中有以下命令:
*/5 * * * * php /var/www/domain/yii rss/parse
它以错误的字符集输出电子邮件:
Content-Type: text/plain; charset=ANSI_X3.4-1968
但是当我直接在 CLI 中启动该命令并将其输出到日志时:
php /var/www/domain/yii rss/parse > log
我得到了正确的编码-UTF-8
已经尝试在 /etc/environment 中设置 lang:
LANG=en_US.UTF-8
重新启动了 cron,但它仍然通过 CRON 使用 ANSI。有什么想法吗?
答案1
通过添加到 crontab 解决了我的问题:
crontab -e
在文件顶部我写道:
CONTENT_TYPE="text/plain; charset=utf-8"
现在,我的所有 cron 作业电子邮件都采用 UTF-8 字符集。
答案2
参考此问题我在 Debian Jessie 的 /etc/default/cron 中发现以下内容:
# Whether to read the system's default environment files (if present)
# If set to "yes", cron will set a proper mail charset from the
# locale information. If set to something other than 'yes', the default
# charset 'C' (canonical name: ANSI_X3.4-1968) will be used.
#
# This has no effect on tasks running under cron; their environment can
# only be changed via PAM or from within the crontab; see crontab(5).
READ_ENV="yes"
换句话说,默认情况下,它在此发行版中读取环境文件。重新运行后dpkg-reconfigure locales
(在我的情况下,默认值已设置为 UTF8),我查看了 /etc/environment 并发现它是空的。一旦我插入LC_ALL=en_US.UTF-8
那里,cron 作业电子邮件就会带有正确的字符集标头。
答案3
我认为,当您通过 CLI 发出命令时,您会得到 utf-8 聊天集,因为您使用的是 MAC OS PC 或 Linux PC
我之所以这么说,是因为您的 PC 的当前 LANG 已在您的 ssh 会话中开始复制
grep -i LANG /etc/ssh/sshd_config
AcceptEnv LANG LANGUAGE LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
来自 man sshd_config
AcceptEnv
Specifies what environment variables sent by the client will be copied into the session’s environ(7). See SendEnv in ssh_config(5) for how to
configure the client. Note that environment passing is only supported for protocol 2. Variables are specified by name, which may contain the
wildcard characters ‘*’ and ‘?’. Multiple environment variables may be separated by whitespace or spread across multiple AcceptEnv directives.
Be warned that some environment variables could be used to bypass restricted user environments. For this reason, care should be taken in the
use of this directive. The default is not to accept any environment variables.
您的 crond 进程正在使用 charset=ANSI_X3.4-1968,也许这是默认的系统 LANG,但如果要更改它
man 5 crontab
答案4
我必须针对所有用户(而不是特定用户)全局解决这个问题。我尝试设置 /etc/environment 和 /etc/default/locale,然后重新启动 cron。这没有帮助。对我来说,正确的答案是在 upstart 脚本中使用 env 命令(我正在运行 ubuntu 服务器):
环境LC_ALL = en_US.UTF-8
cat /etc/init/cron.conf
# cron - regular background program processing daemon
#
# cron is a standard UNIX program that runs user-specified programs at
# periodic scheduled times
description "regular background program processing daemon"
start on runlevel [2345]
stop on runlevel [!2345]
expect fork
respawn
env LC_ALL=en_US.UTF-8
exec cron
然后我重新启动了 cron 并收到了 utf-8 的正确邮件。