Python supbprocess.Popen无法通过cron作业执行带有sudo无密码访问的脚本。为什么?

时间:2016-01-08 14:44:34

标签: python linux shell cron subprocess

我有一个bash脚本,必须从python应用程序中作为另一个用户执行。为此,我为脚本runme.sh设置了sudo访问权限,使用visudo并授予acctA显式访问权限以作为otherAcct运行。如果我从acctA运行python脚本,它按预期执行runme.sh但如果我在crontab中安排runme.sh永远不会执行。我错过了什么?

visudo(sudoers):

acctA ALL = (otherAcct) NOPASSWD: /home/otherAcct/someapp/runme.sh

在python应用程序中,我使用subprocess.Popen运行然后监视stdout并打印到日志。的Python:

#!/usr/bin/python
# -*- coding: ascii -*-
import sys
import os
import subprocess
import threading
import inspect
import time
import datetime

try:
    print(datetime.datetime.today().strftime('%c') + ' - Starting test. ')
    clean_file = "/tmp/testworkfile.txt"
    exec_command = ["sudo", "-u", "otherAcct", "/home/otherAcct/someapp/runme.sh", "-f", clean_file]
    proc = subprocess.Popen(exec_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while proc.poll() == None:
        #logging - print for now
        print('out: ' + proc.stdout.readline())
    print(datetime.datetime.today().strftime('%c') + ' - Test complete. ')
except:
    print('Error: {0}'.format(str(sys.exc_info())))

runme.sh:

#!/bin/bash
thislog=/home/otherAcct/someapp/someapp.log
echo "`date +%Y-%m-%d` `date +%H:%M:%S` - executing runme.sh..." >> $thislog
# reading passed arguments
RUN_FILE=""
while [[ $# > 1 ]]
do
key="$1"

case $key in
        -f|--file)      # file, file passed in with files to be deleted
        RUN_FILE="$2"
        shift
        ;;
        *)
                        # unknown argument, intentionally blank
        ;;
esac
shift
done
# source otherAcct profile to be sure env is set
source /home/otherAcct/.bash_profile
# logging
echo "Check/verify user: $(whoami) " >> $thislog
echo "RUN_FILE input param: $RUN_FILE " >> $thislog
if [[ ! -z $RUN_FILE ]]; then
while IFS='' read -r fline || [[ -n "$fline" ]]; do
echo "deleting file: $fline " >> $thislog
rm $fline
done < "$RUN_FILE"
#
# end CHECK_RUN_FILE
else
echo "$RUN_FILE not found, exitting. "
fi
echo "`date +%Y-%m-%d` `date +%H:%M:%S` - runme.sh complete" >> $thislog

0 个答案:

没有答案