1

My script failed in compare check.decode() == 'TRUE', the result of /healthcheck/bin/captureFailed.sh is TRUE, should enter inside the if, and not fall into the else, any suggetions ?

Script python:

import requests
import json
from time import gmtime, strftime
import subprocess
from subprocess import Popen, PIPE, STDOUT

try:

    p = Popen(['/bin/bash', '/healthcheck/bin/captureFailed.sh'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
    check = p.communicate()[0]
    print("[INFO] CHECK TEPS STATUS: {}".format(check.decode()))

    if str(check.decode()) == 'TRUE':

        print("[INFO] SENDING ALERT")

        webhook_url = 'https://hooks.slack.com/services/channel-here'

        response = requests.post(
            webhook_url,
            json={'text': '[ALERT] Baseline control has not been updated, there is a flaw in TEPS, check the logs. [{}]'
            .format(strftime("%Y-%m-%d", gmtime()))},
            headers={'Content-Type': 'application/json'}
        )

        if response.status_code != 200:
            raise ValueError(
                'Request to slack returned an error %s, the response is:%s'
                % (response.status_code, response.text)
            )

        else:

            print("[OK] SENT WITH SUCCESS")

    else:

        print("[OK] NO ERRORS, RUNNING SCRIPTS ...")


except Exception as e:

    print('[FAILED] Caused by: {}'.format(e))

Script shell:

cat /healthcheck/logs/exec.log | grep HTTP | while read line
do
    echo "$line" | grep "ERROR" >/dev/null
    if [ $? = 0 ]; then
        echo "TRUE";
    fi
done

Output:

[INFO] CHECK TEPS STATUS: TRUE

[OK] NO ERRORS, RUNNING SCRIPTS ...
Luis Henrique
  • 701
  • 15
  • 36

1 Answers1

1

When working with external commands (executed via subprocess or others) output, and in some other cases, it's recommended not to forget that strings (even if they look OK), might contain the "invisible" EOLNs.

Example:

>>> s = "abcd\n"
>>> s
'abcd\n'
>>> len(s)
5
>>> print(s)  # Looks OK
abcd

>>> s == "abcd"
False
>>> s.rstrip() == "abcd"
True

The solution is to strip the end of line, using rstrip().
An additional comment you should only call decode() once.

Below it's the corrected code:

# ...

check = p.communicate()[0].decode()
print("[INFO] CHECK TEPS STATUS: {}".format(check))

if check.rstrip() == "TRUE":

# ...
CristiFati
  • 38,250
  • 9
  • 50
  • 87