У меня есть сценарий sh
, который является прослушивание вывода журнала.
Когда он находит IP-адрес при определенных условиях, ему необходимо отправить запрос curl
на этот IP-адрес (получателем является телефон Polycom VoIP, если это имеет значение).
На приемнике я получаю:
PushParserC :: parseDoc: Expecting
где правильная строка дает следующее:
wappPushHandlerC :: Handle:
и на дампе -v
curl
я получаю:
curl: (6) Не удалось resolve host: priority = "Critical"> Ключ ....
<должен быть IP-адрес
В обоих случаях похоже, что в моем сценарии связь прерывается из-за пробела. Большинство решений избавляются от пробелов, но это нарушает ожидаемый XHTML.
Мой сценарий ниже
#!/bin/sh
tail -0f /var/log/somelogfile.log | while read line
do
if echo $line | grep "\[WARNING\]" | grep -q "SIP auth failure" ; then
# Log detected sip authentication error to file
STR="$(echo $line | awk '{print "Date:",$1,"Time:",$2,"Login:",$14,"IP:",$17}')" >> logger.txt
# Get the found private IP address out of the errored line
IP="$(echo $STR | rev | cut -d" " -f1 | rev)"
# Provide output to the user of the IP to brute
echo "Target IP: " $IP
# Content Type header
CT="Content-Type: application/x-com-polycom-spipx"
# The XHTML to send to the phone in question for forced factory reset
XHTML="curl -v --digest -u Push:Push -d $'<PolycomIPPhone><Data priority=\"Critical\">Key:Setup\nKey:Dialpad2\nKey:Dialpad9\nKey:Dialpad9\nKey:Dialpad9\nKey:Softkey4\nKey:Dialpad1\nKey:Dialpad5\nKey:Dialpad5</Data></PolycomIPPhone>' --header \"$CT\" $IP/push"
# print out URL for test
echo $XHTML
RESPONSE=`$XHTML`
echo
echo $RESPONSE
fi
done
# This is an example of the fuctional code that works straight in the terminal.
# curl --digest -u Push:Push -d $'<PolycomIPPhone><Data priority="Critical">Key:Setup\nKey:Dialpad2\nKey:Dialpad9\nKey:Dialpad9\nKey:Dialpad9\nKey:Softkey4\nKey:Dialpad1\nKey:Dialpad5\nKey:Dialpad5</Data></PolycomIPPhone>' --header "Content-Type: application/x-com-polycom-spipx" xx.xx.xx.xx/push && echo
Другие решения удаляют пробелы, что невозможно в данном контексте или кодировать. Но ни то, ни другое не работает в этом приложении!
Спасибо!
С помощью @Archemar и @dave_thompson_085 я смог создать работающее решение.
Чтобы обойти проблемы с пробелами и новой строкой при отправке или получении, я создал файл с указанным содержимым и «настоящими» символами новой строки. Передача нового файла в curl по-прежнему вызывала у меня те же проблемы, пока я не обнаружил отправку содержимого в виде «формы», которая сохранила форматирование без изменений.
Безусловно, приятно видеть, что такая проблема решается автоматически.
Еще раз спасибо, ребята.
#!/bin/bash
# Sends a data file to the phone using curl
tail -0f /var/log/freeswitch/freeswitch.log | while read line
do
if [[ $line == *\[WARNING\]* && $line == *SIP\ auth\ failure* ]] ; then
STR="$(echo $line | awk '{print "Date:",$1,"Time:",$2,"IP:",$17,"Login:",$14}')" # Pull important lines from log
IP="${line##* }" # Store private IP address of failed auth
CT="Content-Type: application/x-com-polycom-spipx" # Content Type header
OCCUR=`grep "$IP" logger.txt | wc -l` # Count of how many failed attempts to auth
# Provide output to the terminal
echo -n "TargetIP:" $IP
# If there are less than 6 attemps at authenticating, send commands to phone
if [ $OCCUR -le 5 ] ; then
echo " Formatting with" $OCCUR "previous attepts."
# Log the parsed string from the log with attempt status
echo "Status: FORMAT" $STR >> logger.txt
# Send user a HTML warning screen
curl -s --digest -u push:push -d "<PolycomIPPhone><Data priority='"critical"'><h1> PHONE WILL UPDATE </h1>Please do not interact with the phone. It will now format and restart. Contact IT support for any concerns</Data></PolycomIPPhone>" --header $CT $IP/push > /dev/null
# Allow for user read time
sleep 8
# Send instruction set phone in question for forced factory reset
curl -s --digest -u push:push --form "fileupload=@send.txt" --header "$CT" $IP/push > /dev/null
# If there are 6 failed attempts, log to file for further action
elif [ $OCCUR -eq 6 ] ; then
echo " Too many attempts. Logging..."
echo "Status: FAILED" $STR >> logger.txt
# Beyond 6 attemps, no action will be taken
else
echo " IGNORED"
fi
fi
done
для параметра -d
, я бы попробовал
echo '$<PolycomIPPhone><Data priority=\"Critical\">....' | curl -d@- (other options)
согласно man curl
Если вы начнете данные с буква @, остальное должно быть именем файла, из которого будут считываться данные, или - если вы хотите, чтобы curl читал данные из stdin.