IT박스

CRON이 올바른 경로를 호출하도록하는 방법

itboxs 2020. 7. 28. 08:16
반응형

CRON이 올바른 경로를 호출하도록하는 방법


cron이 올바른 PATH를 호출하도록하려고합니다. 쉘에서 Python 스크립트를 실행하면 bashrc에 설정된 PATH를 사용하므로 스크립트가 정상적으로 실행되지만 cron을 사용하면 bashrc에서 모든 PATH가 사용되지 않습니다. bashrc와 같은 cron에 PATH를 입력하거나 bashrc에서 PATH를 호출하는 방법이 있습니까?

죄송합니다.이 단어를 올바르게 작성했다고 생각하지 않습니다. 올바른 스크립트를 실행할 수 있습니다 (crontab의 스크립트에 대한 PATH는 문제가 아닙니다). 스크립트가 실행 중일 때만 빌드를 실행합니다. 경로의 설정 .bashrc. 로그인 할 때 스크립트를 실행하면 .bashrcPATH가 가져옵니다. cron은 셸에서 실행되지 않으므로 끌어 오지 않습니다 .bashrc. bash 스크립트 래퍼를 작성할 필요없이 이것을 끌어내는 방법이 있습니까?


나는 사용했다 /etc/crontab. vi이 파일에 필요한 PATH를 사용 하여 루트로 실행했습니다. 일반 crontab은 설정 한 PATH를 덮어 씁니다. 이 작업을 수행하는 방법에 대한 좋은 자습서 .

시스템 전체 cron 파일은 다음과 같습니다.

This has the username field, as used by /etc/crontab.
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file.
# This file also has a username field, that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user   command
42 6 * * *   root    run-parts --report /etc/cron.daily
47 6 * * 7   root    run-parts --report /etc/cron.weekly
52 6 1 * *   root    run-parts --report /etc/cron.monthly
01 01 * * 1-5 root python /path/to/file.py

크론이 매우 드문 환경에서 실행되고있을 가능성이 높습니다. 다음 env과 같이 파일에 덤프하는 더미 작업을 추가하여 cron이 사용하는 환경 변수를 확인하십시오 .

* * * * * env > env_dump.txt

env일반 쉘 세션 의 출력과 비교하십시오 .

crontab의 맨 위에 변수를 정의하여 고유 한 환경 변수를 로컬 crontab 앞에 추가 할 수 있습니다.

$PATH현재 crontab 앞에 추가하는 빠른 수정 사항은 다음과 같습니다 .

# echo PATH=$PATH > tmp.cron
# echo >> tmp.cron
# crontab -l >> tmp.cron
# crontab tmp.cron

결과 crontab은 chrissygormley의 답변과 유사하며 crontab 규칙 전에 PATH가 정의되어 있습니다.


에 전체 경로를 입력해야합니다 crontab. 이것이 가장 안전한 옵션입니다.
원하지 않는 경우 래퍼 스크립트를 프로그램 주위에 넣고 PATH를 설정할 수 있습니다.

예 :

01 01 * * * command

된다 :

01 01 * * * /full/path/to/command

또한 from에서 호출되는 cron것은 실행되는 프로그램에 매우 신중해야하며 PATH변수에 대한 자체 선택을 설정해야 합니다.

편집하다:

명령이 어디 있는지 모르는 경우 which <command>쉘에서 실행 하고 경로를 알려줍니다.

EDIT2 :

프로그램이 실행되면 그래서, 가장 먼저 할 일은이 설정 PATH및 기타 필요한 변수 (예를 들어, LD_LIBRARY_PATH스크립트를 실행하는 데 필요한 값).
기본적으로 프로그램 / 스크립트에 더 적합하도록 cron 환경을 수정하는 방법을 생각하는 대신 스크립트가 시작될 때 적절한 환경을 설정하여 주어진 환경을 처리하도록하십시오.


변수가 당신을 위해 작동하도록하십시오, 이것은 접근을 허용합니다

/etc/profile.d/*.sh에서 PATH를 정의하십시오.

시스템 전체 환경 변수

/etc/profile.d 디렉토리에 확장자가 .sh 인 파일은 bash 로그인 쉘이 입력 될 때마다 (예 : 콘솔 또는 ssh를 통해 로그인 할 때) 데스크탑 세션이로드 될 때 DisplayManager에 의해 실행됩니다.

예를 들어 /etc/profile.d/myenvvars.sh 파일을 작성하고 다음과 같이 변수를 설정할 수 있습니다.

export JAVA_HOME=/usr/lib/jvm/jdk1.7.0
export PATH=$PATH:$JAVA_HOME/bin

로그인 옵션으로 crontab을 실행하십시오!

환경 변수를 사용하여 CRONTAB 실행 스크립트 또는 명령

0 9 * * * cd /var/www/vhosts/foo/crons/; bash -l -c 'php -f ./download.php'
0 9 * * * cd /var/www/vhosts/foo/crons/; bash -l -c download.sh

내 crontab의 명령 줄 바로 앞에 PATH를 설정하면 나에게 도움이되었습니다.

* * * * * PATH=$PATH:/usr/local/bin:/path/to/some/thing

올바른 값으로 사용자 crontab에 PATH 정의를 추가하면 도움이 될 것입니다 ...

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

그리고 모든 스크립트를 작동시키는 것으로 충분합니다 ... 필요한 경우 사용자 정의 경로를 포함하십시오.


문제

스크립트는 콘솔에서 실행할 때 작동하지만 cron에서는 실패합니다.

원인

crontab에 올바른 경로 변수 (및 가능하면 쉘)가 없습니다

해결책

현재 쉘 추가 및 crontab 경로

당신을 위해 그것을 할 스크립트

#!/bin/bash
#
# Date: August 22, 2013
# Author: Steve Stonebraker
# File: add_current_shell_and_path_to_crontab.sh
# Description: Add current user's shell and path to crontab
# Source: http://brakertech.com/add-current-path-to-crontab
# Github: hhttps://github.com/ssstonebraker/braker-scripts/blob/master/working-scripts/add_current_shell_and_path_to_crontab.sh

# function that is called when the script exits (cleans up our tmp.cron file)
function finish { [ -e "tmp.cron" ] && rm tmp.cron; }

#whenver the script exits call the function "finish"
trap finish EXIT

########################################
# pretty printing functions
function print_status { echo -e "\x1B[01;34m[*]\x1B[0m $1"; }
function print_good { echo -e "\x1B[01;32m[*]\x1B[0m $1"; }
function print_error { echo -e "\x1B[01;31m[*]\x1B[0m $1"; }
function print_notification { echo -e "\x1B[01;33m[*]\x1B[0m $1"; }
function printline { 
  hr=-------------------------------------------------------------------------------------------------------------------------------
  printf '%s\n' "${hr:0:${COLUMNS:-$(tput cols)}}"
}
####################################
# print message and exit program
function die { print_error "$1"; exit 1; }

####################################
# user must have at least one job in their crontab
function require_gt1_user_crontab_job {
        crontab -l &> /dev/null
        [ $? -ne 0 ] && die "Script requires you have at least one user crontab job!"
}


####################################
# Add current shell and path to user's crontab
function add_shell_path_to_crontab {
    #print info about what's being added
    print_notification "Current SHELL: ${SHELL}"
    print_notification "Current PATH: ${PATH}"

    #Add current shell and path to crontab
    print_status "Adding current SHELL and PATH to crontab \nold crontab:"

    printline; crontab -l; printline

    #keep old comments but start new crontab file
    crontab -l | grep "^#" > tmp.cron

    #Add our current shell and path to the new crontab file
    echo -e "SHELL=${SHELL}\nPATH=${PATH}\n" >> tmp.cron 

    #Add old crontab entries but ignore comments or any shell or path statements
    crontab -l | grep -v "^#" | grep -v "SHELL" | grep -v "PATH" >> tmp.cron

    #load up the new crontab we just created
    crontab tmp.cron

    #Display new crontab
    print_good "New crontab:"
    printline; crontab -l; printline
}

require_gt1_user_crontab_job
add_shell_path_to_crontab

출처

https://github.com/ssstonebraker/braker-scripts/blob/master/working-scripts/add_current_shell_and_path_to_crontab.sh

샘플 출력

add_curent_shell_and_path_to_crontab.sh example output


내 AIX cron에서 .profile에 설정된 것을 무시하고 / etc / environment에서 환경 변수를 선택합니다.

편집 : 또한 다양한 연령대의 Linux 상자 두 개를 확인 했으며이 파일 도이 파일을 가지고있는 것처럼 보이므로 AIX와 관련이 없습니다.

joemaller의 cron 제안을 사용하여 이것을 확인하고 / etc / environment에서 PATH 변수를 편집하기 전후에 출력을 확인했습니다.


The default environment for cron jobs is very sparse and may be very different from the environment you develop your python scripts in. For a script that might be run in cron, any environment that you depend on should be set explicitly. In the cron file itself, include full paths to python executables and to your python scripts.


I know this has been answered already, but I thought that his would be useful to some. I had a similar issue that I recently solved (found here) and here are the highlights of the steps I took to answer this question:

  1. make sure that you have the variables you need in PYTHONPATH (found here and here and for more info here) inside the .profile or .bash_profile for any shell you want to test your script in to make sure it works.

  2. edit your crontab to include the directories needed to run your script in a cron job (found here and here)

    a) be sure to include the root directory in the PATH variable (.) as explained here (basically if you are running an executable with your command it needs to be able to find root or the directory where the executable is stored) and probably these (/sbin:/bin:/usr/sbin:/usr/bin)

  3. in your crontab file, create a cronjob that will change directory to the directory where you have successfully ran the script before (i.e. Users/user/Documents/foo)

    a) This will look like the following:

    * * * * cd /Users/user/Documents/foo; bar -l doSomething -v 
    

If you don't want to have to make the same edits in various places, then roughly do this:

* * * * * . /home/username/.bashrc && yourcommand all of your args

The . space and then the path to .bashrc and the && command are the magic there to get your environment changes into the running bash shell. Too, if you really want the shell to be bash, it is a good idea to have a line in your crontab:

SHELL=/bin/bash

Hope it helps someone!


@Trevino: your answer helped me solve my problem. However, for a beginner, trying to give a step by step approach.

  1. Get your current installation of java via $ echo $JAVA_HOME
  2. $ crontab -e
  3. * * * * * echo $PATH - this lets you understand whats the PATH value being used by crontab at present. Run crontab and grab $PATH value used by crontab.
  4. Now edit crontab again to set your desired java bin path: a) crontab -e; b) PATH=<value of $JAVA_HOME>/bin:/usr/bin:/bin (its a sample path); c) now your scheduled job/script like */10 * * * * sh runMyJob.sh &; d) remove echo $PATH from crontab as its not needed now.

The simplest workaround I've found looks like this:

* * * * * root su -l -c command

This example invokes su as root user and starts the shell with the user's full environment, including $PATH, set as if they were logged in. It works the same on different distros, is more reliable than sourcing .bashrc (which hasn't worked for me) and avoids hardcoding specific paths which can be a problem if you're providing an example or setup tool and don't know what distro or file layout on the user's system.

You can also specify the username after su if you want a different user than root, but you should probably leave the root parameter before su command since this ensures su has sufficient privileges to switch to any user you specify.


Set the required PATH in your cron

crontab -e

Edit: Press i

PATH=/usr/local/bin:/usr/local/:or_whatever

10 * * * * your_command

Save and exit :wq


Should you use webmin then these are the steps how to set the PATH value:

System
  -> Scheduled Cron Jobs
       -> Create a new environment variable
            -> For user: <Select the user name>
            -> Variable name: PATH
            -> Value: /usr/bin:/bin:<your personal path>
            -> Add environment variable: Before all Cron jobs for user

참고URL : https://stackoverflow.com/questions/2388087/how-to-get-cron-to-call-in-the-correct-paths

반응형