This commit is contained in:
Hubert Cornet 2023-07-04 13:06:44 +02:00
parent bffa3e84e8
commit 51385f2bd0
7 changed files with 1136 additions and 4 deletions

150
LICENSE
View File

@ -1,3 +1,149 @@
Additional permission under GNU GPL version 3 section 7 gitGNU Free Documentation License
Version 1.3, 3 November 2008
If you modify this Program, or any covered work, by linking or combining it with [name of library] (or a modified version of that library), containing parts covered by the terms of [name of library's license], the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of [name of library] used as well as that of the covered work. Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
0. PREAMBLE
The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.
This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
1. APPLICABILITY AND DEFINITIONS
This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.
A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.
A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.
The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.
The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.
A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque".
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.
The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.
The "publisher" means any person or entity that distributes copies of the Document to the public.
A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.
2. VERBATIM COPYING
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly display copies.
3. COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
4. MODIFICATIONS
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:
A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.
B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.
C. State on the Title page the name of the publisher of the Modified Version, as the publisher.
D. Preserve all the copyright notices of the Document.
E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.
F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.
G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. H. Include an unaltered copy of this License.
I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence.
J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission.
K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.
L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.
M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified Version.
N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section.
O. Preserve any Warranty Disclaimers.
If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.
You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
5. COMBINING DOCUMENTS
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements".
6. COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
7. AGGREGATION WITH INDEPENDENT WORKS
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.
8. TRANSLATION
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.
If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
9. TERMINATION
You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License.
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.
10. FUTURE REVISIONS OF THIS LICENSE
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document.
11. RELICENSING
"Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site.
"CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization.
"Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document.
An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008.
The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.
ADDENDUM: How to use this License for your documents
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
Copyright (c) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this:
with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.

432
Pi-Hole/Check-PiHole-Api.sh Normal file
View File

@ -0,0 +1,432 @@
#!/bin/bash
# Centreon plugin to work with Pihole API
############ By @tips-of-mine ############
plugin_version="1.0"
##########################################
red=$'\033[1;31m'
yellow=$'\033[0;33m'
nc=$'\033[0m'
current_dira="$(pwd)"
current_dir="/usr/lib/centreon/plugins"
function info() {
case "$1" in
token)
echo " "
echo " ************************************************************************************************"
echo " *"
echo " * The file ${yellow}${api_token_file}${nc} does not exist or it's empty."
echo " * You can get your token from the value ${yellow}WEBPASSWORD${nc} in the file ${yellow}/etc/pihole/setupVars.conf${nc}"
echo " * Just put in the file ${yellow}${api_token_file}${nc} and that's it."
echo " *"
echo " * Example:"
echo " * centreon-engine@centreon # ${yellow}touch ${api_token_file}${nc}"
echo " * centreon-engine@centreon # ${yellow}echo 'PASTE_YOUR_TOKEN_HERE' >> ${api_token_file}${nc}"
echo " *"
echo " ************************************************************************************************"
echo " "
exit 1 ;
;;
usage)
echo " "
echo " ************************************************************************************************"
echo " *"
echo " * Instructions for use"
echo " *"
echo " ************************************************************************************************"
echo " *"
echo " * Usage $0 -h pihole_ipaddress -e [ ads || being || clients || queries || unique] || -s || -i || -q || -t "
echo " *"
echo " * -h (host) "
echo " * - ip address or fqdn name of the machine running Pi-Hole "
echo " *"
echo " * -c (cache) "
echo " * - show cache "
echo " *"
echo " * -e (summary) "
echo " * - ads : Number and percentage of ads blocked. "
echo " * - being : Amount of blocked domain."
echo " * - clients : Number of clients using Pihole as their DNS server "
echo " * - domain : Number of domain queries "
echo " * - queries : Number of DNS queries "
echo " *"
echo " * -f (forwarded) "
echo " * - show forwarded "
echo " *"
echo " * -r (reply) "
echo " * - show the status reply UNKNOWN, CNAME, IP, NODATA, NXDOMAIN "
echo " *"
echo " * -s (status) "
echo " * - show the status service (enable/disable) "
echo " *"
echo " * -q (querie) "
echo " * - queries by type AAAA, A, SOA, TXT, PTR, ANY, SRV, IPV4, IPV6 "
echo " *"
echo " * -t (top 10) "
echo " * - Show a TOP number of queries by host "
echo " *"
echo " * -v (information) "
echo " * - show the version of the plugin "
echo " *"
echo " ************************************************************************************************"
echo " "
exit 0 ;
;;
version)
echo " "
echo " ************************************************************************************************"
echo " *"
echo " * Plugin by @tips-of-mine https://git.tips-of-mine.fr/ - Version: ${plugin_version} "
echo " *"
echo " ************************************************************************************************"
echo " "
exit 0 ;
;;
esac
}
function ApiCall() {
local obj=$1
local token=$2
pihole_api_tempfile="/tmp/pihole_api_${obj}.tmp"
case $obj in
"summary")
pihole_api_output=$(curl "http://${pihole_ipadd}/admin/api.php?${obj}&auth=${token}" 2> /dev/null | sed 's/{/\n/g ; s/","/\n/g ; s/"//g' > ${pihole_api_tempfile})
;;
"status")
pihole_api_output=$(curl "http://${pihole_ipadd}/admin/api.php?${obj}&auth=${token}" 2> /dev/null | sed 's/","/\n/g ; s/"//g' > ${pihole_api_tempfile})
;;
"getQueryTypes")
pihole_api_output=$(curl "http://${pihole_ipadd}/admin/api.php?${obj}&auth=${token}" 2> /dev/null | sed "s,),,g ; s,(,,g ; s/,\"/\n/g ; s/\"//g" > ${pihole_api_tempfile})
;;
"getQuerySources")
pihole_api_output=$(curl "http://${pihole_ipadd}/admin/api.php?${obj}&auth=${token}" 2> /dev/null | sed 's,{"top_sources":{",,g ; s/,"/\n/g ; s/"//g ; s/}//g ; s/|/:/g' > ${pihole_api_tempfile})
esac
}
function GetApiToken() {
# Default token file location
api_token_file="${current_dir}/pihole-api.token"
# If the file does not exist
if [ ! -f ${api_token_file} ]; then
echo " "
echo " ************************************************************************************************"
echo " *"
echo " * ${red}The file ${api_token_file} does not exist ${nc}"
echo " *"
echo " ************************************************************************************************"
echo " ";
info token
else
export api_token=$(cat ${api_token_file})
# If the the api_token var is NULL because the file is empty (?)
if [ -z ${api_token} ]; then
echo " "
echo " ************************************************************************************************"
echo " *"
echo " * ${red}The file ${api_token_file} exists, but it is empty ${nc}"
echo " *"
echo " ************************************************************************************************"
echo " ";
info token
fi
fi
}
function functSummary() {
# This function requires a token
GetApiToken
# The summary option passed
ApiCall "summary" "${api_token}"
case "${summary_opt}" in
ads)
ads_percentage_today=$(cat ${pihole_api_tempfile} | grep ads_percentage_today | cut -f2 -d":")
ads_blocked_today=$(cat ${pihole_api_tempfile} | grep ads_blocked_today | cut -f2 -d":")
echo "ADS blocked today : ${ads_blocked_today}, Percentage = ${ads_percentage_today} % | 'TotalADS'=${ads_blocked_today} 'Percentage'=${ads_percentage_today}%"
;;
being)
domains_being_blocked=$(cat ${pihole_api_tempfile} | grep domains_being_blocked | cut -f2 -d":")
echo "Domains blocked : ${domains_being_blocked} | 'Blocked'=${domains_being_blocked}"
;;
clients)
unique_clients=$(cat ${pihole_api_tempfile} | grep unique_clients | cut -f2 -d":")
clients_ever_seen=$(cat ${pihole_api_tempfile} | grep clients_ever_seen | cut -f2 -d":")
echo "${unique_clients} Hosts up, Total ${clients_ever_seen} | 'Hosts'=${unique_clients} 'TotalHosts'=${clients_ever_seen}"
;;
domain)
unique_domains=$(cat ${pihole_api_tempfile} | grep unique_domains | cut -f2 -d":")
echo "Queries domain : ${unique_domains} | 'QueryDomain'=${unique_domains}"
;;
queries)
dns_queries_today=$(cat ${pihole_api_tempfile} | grep dns_queries_today | cut -f2 -d":")
dns_queries_all_types=$(cat ${pihole_api_tempfile} | grep dns_queries_all_types | cut -f2 -d":")
echo "DNS queries today : ${dns_queries_today}, queries all type : ${dns_queries_all_types} | 'DnsTotalToday'=${dns_queries_today} 'DnsAllType'=${dns_queries_all_types}"
;;
*)
echo " "
echo " ************************************************************************************************"
echo " *"
echo " * ${red}Incorrect arugment > ${summary_opt} < for the option -s ${nc}"
echo " *"
echo " ************************************************************************************************"
echo " ";
info "usage"
exit 1 ;
;;
esac
}
function functCache() {
# This function requires a token
GetApiToken
# Calling the api
ApiCall "summary" "${api_token}"
#
queries_cached=$(cat ${pihole_api_tempfile} | grep -io "queries_cached:.*" | cut -f2 -d":" | sed 's/}//g')
#
echo "Use cache ${queries_cached} | 'cache'=${queries_cached} "
}
function functforwarded() {
# This function requires a token
GetApiToken
# Calling the api
ApiCall "summary" "${api_token}"
#
queries_forwarded=$(cat ${pihole_api_tempfile} | grep -io "queries_forwarded:.*" | cut -f2 -d":" | sed 's/}//g')
#
echo "Use forwarded ${queries_forwarded} | 'forwarded'=${queries_forwarded} "
}
function functStatus() {
# This function requires a token
GetApiToken
# Calling the api
ApiCall "status" "${api_token}"
#
status=$(cat ${pihole_api_tempfile} | grep -io "status:.*" | cut -f2 -d":" | sed 's/}//g')
#
if [[ ${status} == "enabled" ]]; then
echo "OK - Status Pi-Hole is ${status} | 'enabled'=1, 'disabled'=0 "
exit 0;
elif [[ ${status} == "disabled" ]]; then
echo "WARNING - Status Pi-Hole is ${status} | 'enabled'=0, 'disabled'=1 "
exit 1;
else
echo "UNKNOWN - Status Pi-Hole is ${status} | 'enabled'=0, 'disabled'=0 "
exit 3;
fi
}
function functGetReply() {
# This function requires a token
GetApiToken
# Calling the api
ApiCall "summary" "${api_token}"
# Local vars for query types
local reply_UNKNOWN=$(cat ${pihole_api_tempfile} | grep reply_UNKNOWN | cut -f2 -d":")
local reply_NODATA=$(cat ${pihole_api_tempfile} | grep reply_NODATA | cut -f2 -d":")
local reply_NXDOMAIN=$(cat ${pihole_api_tempfile} | grep reply_NXDOMAIN | cut -f2 -d":")
local reply_CNAME=$(cat ${pihole_api_tempfile} | grep reply_CNAME | cut -f2 -d":")
local reply_IP=$(cat ${pihole_api_tempfile} | grep reply_IP | cut -f2 -d":")
local reply_DOMAIN=$(cat ${pihole_api_tempfile} | grep reply_DOMAIN | cut -f2 -d":")
texte="'UNKNOWN'=${reply_UNKNOWN}, 'NODATA'=${reply_NODATA}, 'NXDOMAIN'=${reply_NXDOMAIN}, 'CNAME'=${reply_CNAME}, 'IP'=${reply_IP}, 'DOMAIN'=${reply_DOMAIN}"
datatexte="'UNKNOWN'=${reply_UNKNOWN}, 'NODATA'=${reply_NODATA}, 'NXDOMAIN'=${reply_NXDOMAIN}, 'CNAME'=${reply_CNAME}, 'IP'=${reply_IP}, 'DOMAIN'=${reply_DOMAIN}"
echo "Reply type ${texte} | ${datatexte}"
}
function functGetQueryTypes() {
# This function requires a token
GetApiToken
# Calling the api
ApiCall "getQueryTypes" "${api_token}"
# Local vars for query types
local ipv4=$(cat ${pihole_api_tempfile} | grep -io "ipv4:.*" | cut -f2 -d":")
local ipv6=$(cat ${pihole_api_tempfile} | grep -io "ipv6:.*" | cut -f2 -d":")
local any=$(cat ${pihole_api_tempfile} | grep -io "any:.*" | cut -f2 -d":")
local srv=$(cat ${pihole_api_tempfile} | grep -io "srv:.*" | cut -f2 -d":")
local soa=$(cat ${pihole_api_tempfile} | grep -io "soa:.*" | cut -f2 -d":")
local ptr=$(cat ${pihole_api_tempfile} | grep -xi "ptr:.*" | cut -f2 -d":")
local naptr=$(cat ${pihole_api_tempfile} | grep -io "naptr:.*" | cut -f2 -d":")
local txt=$(cat ${pihole_api_tempfile} | grep -io "txt:.*" | sed 's,},,g' | cut -f2 -d":")
local mx=$(cat ${pihole_api_tempfile} | grep -io "mx:.*" | sed 's,},,g' | cut -f2 -d":")
local ds=$(cat ${pihole_api_tempfile} | grep -io "ds:.*" | sed 's,},,g' | cut -f2 -d":")
local rrsig=$(cat ${pihole_api_tempfile} | grep -io "rrsig:.*" | sed 's,},,g' | cut -f2 -d":")
local dnskey=$(cat ${pihole_api_tempfile} | grep -io "ns:.*" | sed 's,},,g' | cut -f2 -d":")
local ns=$(cat ${pihole_api_tempfile} | grep -io "ns:.*" | sed 's,},,g' | cut -f2 -d":")
local other=$(cat ${pihole_api_tempfile} | grep -io "other:.*" | sed 's,},,g' | cut -f2 -d":")
local svcb=$(cat ${pihole_api_tempfile} | grep -io "svcb:.*" | sed 's,},,g' | cut -f2 -d":")
texte="'IPV4'=${ipv4}, 'IPV6'=${ipv6}, 'ANY'=${any}, 'SRV'=${srv}, 'SOA'=${soa}, 'PTR'=${ptr}, 'NAPTR'=${naptr}, 'TXT'=${txt}, 'MX'=${mx}, 'DS'=${ds}, 'RRSIG'=${rrsig}, 'DNSKEY'=${dnskey}, 'NS'=${ns}, 'OTHER'=${other}, 'SVCB'=${svcb}"
datatexte="'IPV4'=${ipv4}, 'IPV6'=${ipv6}, 'ANY'=${any}, 'SRV'=${srv}, 'SOA'=${soa}, 'PTR'=${ptr}, 'NAPTR'=${naptr}, 'TXT'=${txt}, 'MX'=${mx}, 'DS'=${ds}, 'RRSIG'=${rrsig}, 'DNSKEY'=${dnskey}, 'NS'=${ns}, 'OTHER'=${other}, 'SVCB'=${svcb}"
echo "Number of queries by type ${texte} | ${datatexte}"
}
function functGetQuerySources() {
# This function requires a token
GetApiToken
# Calling the api
ApiCall "getQuerySources" "${api_token}"
while read line; do
check_columns=$(echo $line | sed 's,:, ,g' | wc -w)
host_name=$(echo $line | cut -f1 -d":")
if [[ "${check_columns}" == "3" ]]; then
columns="3"
elif [[ "${check_columns}" == "2" ]]; then
columns="2"
else
echo "Error formatting the list"
echo " "
exit 1;
fi
host_queries=$(echo ${line} | cut -f${columns} -d":")
if [ -z "${host_queries}" ]; then host_queries="0"; fi
texte="${texte} ${host_name}=${host_queries}\n"
datatexte="${datatexte} ${host_name}=${host_queries}"
done < ${pihole_api_tempfile}
echo -e "Top hosts by queries :\n${texte}|${datatexte}"
}
# Display if there is no argument
if [ $# -eq 0 ]; then
info "usage"
exit 1;
fi
# The options passed by the user
while getopts "h:e:cfqrstv" opt; do
case "$opt" in
h )
pihole_ipadd=${OPTARG} ;;
c )
e )
summary_selected="y"
summary_opt=${OPTARG} ;;
f )
query_forwarded="y" ;;
q )
query_type_selected="y" ;;
r )
query_type_reply="y" ;;
s )
status="y" ;;
t )
query_sources_selected="y" ;;
v )
info "version"
exit 0 ;;
\?)
echo " "
echo " ************************************************************************************************"
echo " *"
echo " * ${red}Invalid option. -${OPTARG} ${nc}"
echo " *"
echo " * use -h to get help "
echo " *"
echo " ************************************************************************************************"
echo " "
exit 1 ;;
esac
done
# The values passed by the user
if [ -z ${pihole_ipadd} ]; then
echo " "
echo " ************************************************************************************************"
echo " *"
echo " * ${red}Please enter the Pihole IP address as follow: -h pihole_ipaddress ${nc}"
echo " *"
echo " ************************************************************************************************"
echo " ";
exit 1;
else
if [[ "${summary_selected}" == "y" ]]; then
# Calling the summary function
functSummary
exit 0;
elif [[ "${query_cached}" == "y" ]]; then
# Calling the status Cache
functCache
exit 0;
elif [[ "${status}" == "y" ]]; then
# Calling the status service
functStatus
exit 0;
elif [[ "${query_forwarded}" == "y" ]]; then
# Calling the status forwarded
functforwarded
exit 0;
elif [[ "${query_type_selected}" == "y" ]]; then
# Calling the Query Types funct
functGetQueryTypes
exit 0;
elif [[ "${query_sources_selected}" == "y" ]]; then
# Calling the Query Source funct
functGetQuerySources
exit 0;
elif [[ "${query_type_reply}" == "y" ]]; then
# Calling the Query Reply funct
functGetReply
exit 0;
else
info "usage"
fi
# Just delete the temp file
#rm -f ${pihole_api_tempfile}
fi

54
Pi-Hole/README.md Normal file
View File

@ -0,0 +1,54 @@
# Centreon (or Nagios) Plugin for the Pi-Hole API
![picture](https://www.tips-of-mine.fr/wp-content/uploads/2023/04/logo.jpg)
A set of probes to extract a lot of information from a Pi-hole device through its API.
## Installation
- Copy the script in the ***"/usr/lib/centreon/plugin"*** folder
#### Find Pi-Hole token
- Connect to your Pihole equipment
- Get the token with the value ***WEBPASSWORD*** from the file `cat /etc/pihole/setupVars.conf | grep WEBPASSWORD`.
<br />
- Connect to your Centreon or Nagios device
- put it in `/usr/lib/centreon/plugin`.
centreon-engine@centreon # touch pihole-api.token <br />
centreon-engine@centreon # echo 'PASTE_YOUR_TOKEN_HERE' >> pihole-api.token <br />
## Usage
+ Usage `./check_pihole_api -h pihole_ipaddress -e [ads || being || clients || queries ] || -c || -f || -q || -r || -s || -t || -v`
+ ***-h***
ip address or fqdn name of the machine running Pi-Hole
+ ***-c*** (cache)
show cache use
+ ***-e*** (summary)
+ ***ads*** : Number and percentage of ads blocked.
+ ***being*** : Amount of blocked domain.
+ ***clients***: Number of clients using Pihole as their DNS server
+ ***queries***: Number of DNS queries
+ ***-f*** (forwarded)
show forwarded use
+ ***-q*** (querie)
queries by type AAAA, A, SOA, TXT, PTR, ANY, SRV, IPV4, IPV6, MX, DS, RRSIG, DNSKEY, NS, OTHER, SVCB
+ ***-r*** (reply)
queries by reply UNKNOWN, NODATA, NXDOMAIN, CNAME, IP, DOMAIN
+ ***-s*** (status)
show the status service (enable/disable)
+ ***-t*** (top 10)
Show a TOP number of queries by host
+ ***-v*** (information)
show the version of the plugin
## Centreon
![picture](https://www.tips-of-mine.fr/wp-content/uploads/2023/04/2023-04-23-13_53_12-Centreon-IT-Network-Monitoring-—-Mozilla-Firefox.png)
## More info
- more information on the website [Tips-Of-Mine](https://www.tips-of-mine.fr/?p=1837)
## Buy me a coffe
<a href='https://ko-fi.com/R5R2KNI3N' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://storage.ko-fi.com/cdn/kofi4.png?v=3' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>

View File

@ -1,3 +1,3 @@
# Template # Monitoring
dépôt Template Scripts pour effectuer du monitoring sur des éléments précis

View File

@ -0,0 +1,443 @@
#! /bin/bash
# Script pour vérifier la vitesse de la connexion Internet en utilisant speedtest
#########################################################################################################################################################
#
# Centreon Exit Codes
#
# 0 = OK = Le plugin a pu vérifier le service et il semble fonctionner correctement.
# 1 = Warning = Le plugin a pu vérifier le service, mais il semblait dépasser un certain seuil d'alerte ou ne pas fonctionner correctement.
# 2 = Critical = Le plugin a détecté que le service n'était pas en cours d'exécution ou qu'il dépassait un certain seuil critique
# 3 = Unknown = Des arguments de ligne de commande non valides ont été fournis au plugin ou des défaillances de bas niveau internes au plugin
#
########################################################################################################################################################
############ By @tips-of-mine ############
plugin_name="Centreon speedtest plugin"
version="1.0"
#####################################################################
#
# CHANGELOG
#
# Version 1.0 - Initial Release
#
#####################################################################
red=$'\033[1;31m'
yellow=$'\033[0;33m'
green=$'\033[0;32m'
nc=$'\033[0m'
# function to output script usage
usage()
{
cat << EOF
******************************************************************************************
$plugin_name - Version: $version
OPTIONS :
-h Afficher ce message
-w Niveau d'alerte Warning du téléchargement ${yellow}- *Nécessaire* -${nc} nombre entier ou virgule flottante
-c Niveau d'alerte Crtique du téléchargement ${yellow}- *Nécessaire* -${nc} nombre entier ou virgule flottante
-W Niveau d'alerte Warning de l'Upload ${yellow}- *Nécessaire* -${nc} nombre entier ou virgule flottante
-C Niveau d'alerte Crtique de l'Upload ${yellow}- *Nécessaire* -${nc} nombre entier ou virgule flottante
-l Emplacement du serveur speedtest ${yellow}- *Nécessaire * -${nc}
Si on mets "a" la selection est automatique.
-p Données sur les performances de sortie
-m Niveau Download Maximum ${yellow}- *Nécessaire si vous demandez des perfdata* -${nc} nombre entier ou virgule flottante
-M Niveau Upload Maximum ${yellow}- *Nécessaire si vous demandez des perfdata* -${nc} nombre entier ou virgule flottante
-v Version du plugin
-V Informations de débogage pour les tests
Ce script va envoyer à Centreon la vitesse de la connexion Internet en utilisant speedtest.
Vous devez d'abord installer speedtest sur votre système.
https://install.speedtest.net/app/cli/ookla-speedtest-1.2.0-linux-x86_64.tgz
Voir ici : https://github.com/sivel/speedtest-cli pour des informations sur speedtest
Tout d'abord, vous DEVEZ définir l'emplacement de votre installation speedtest dans le script, sinon cela ne fonctionnera pas.
Pour obtenir id d'un serveur réponse faire la commande
${yellow}./speedtest -L${nc}
Le speedtest peut prendre un certain temps pour renvoyer son résultat.
- Vous devez également avoir accès à bc sur votre système pour que ce script fonctionne.
- Vous devez également avoir accès à jq sur votre système pour que ce script fonctionne.
Vos niveaux d'alerte doivent être plus élevés que vos niveaux critiques, tant pour le chargement que pour le téléchargement.
Les données de performance indiquent la vitesse de téléchargement en amont et en aval par rapport aux niveaux d'alerte et aux niveaux critiques correspondants.
******************************************************************************************
EOF
}
#####################################################################
# Permettant de générer une erreur si l'emplacement binaire du speedtest n'est pas défini
locundef()
{
cat << EOF
******************************************************************************************
$plugin_name - Version: $version
${red}
Vous n'avez pas défini l'emplacement du binaire speedtest dans le script !
Vous DEVEZ le faire le faire avant d'exécuter le script !
Voir la ligne 149 du script !
${nc}
******************************************************************************************
EOF
}
#####################################################################
# Permettant de vérifier si une variable est numérique
# Attend la variable à vérifier comme premier argument
isnumeric()
{
re='^[0-9]+([.][0-9]+)?$'
if ! [[ $1 =~ $re ]]; then
echo "${red}"$2" avec une valeur de : "$1" n'est pas un nombre !${nc}"
usage
exit 3
fi
}
#####################################################################
# Échelle par défaut utilisée par les fonctions flottantes.
float_scale=2
#####################################################################
# Évaluer une expression en virgule flottante.
function float_eval()
{
local stat=0
local result=0.0
if [[ $# -gt 0 ]]; then
result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
stat=$?
if [[ $stat -eq 0 && -z "$result" ]]; then stat=1; fi
fi
echo $result
return $stat
}
#####################################################################
# Évaluer une expression conditionnelle en virgule flottante.
function float_cond()
{
local cond=0
if [[ $# -gt 0 ]]; then
cond=$(echo "$*" | bc -q 2>/dev/null)
if [[ -z "$cond" ]]; then cond=0; fi
if [[ "$cond" != 0 && "$cond" != 1 ]]; then cond=0; fi
fi
local stat=$((cond == 0))
return $stat
}
# Configurer la variable pour l'emplacement du binaire speedtest.
# Modifiez la ligne ci-dessous pour que la variable soit définie comme l'emplacement de speedtest sur votre système
# Sur le mien, il s'agit de /usr/lib/centreon/plugins .
# Veillez à ce que la dernière barre oblique soit supprimée !
# Vous DEVEZ définir cette variable, sinon le script ne s'exécutera pas !
STb=/usr/lib/centreon/plugins
# Configurer les variables pour qu'elles prennent en compte les arguments
DLw=
DLc=
ULw=
ULc=
Loc=
PerfData=
MaxDL=
MaxUL=
debug=
# Recuperer les arguments a l aide de getopts
while getopts "h:w:c:W:C:l:p:m:M:vV" OPTION
do
case $OPTION in
h)
usage
exit 3
;;
w)
DLw=$OPTARG
;;
c)
DLc=$OPTARG
;;
W)
ULw=$OPTARG
;;
C)
ULc=$OPTARG
;;
l)
Loc=$OPTARG
;;
p)
PerfData="TRUE"
;;
m)
MaxDL=$OPTARG
;;
M)
MaxUL=$OPTARG
;;
v)
echo "$plugin_name. Numero de version : $version"
exit 3
;;
V)
debug="TRUE"
;;
esac
done
# Vérifie si la variable binaire Speedtest $STb a été définie
# Quitte avec un avertissement si ce n'est pas le cas.
if [[ -z $STb ]]
then
locundef
exit 3
fi
# Vérifier si les arguments sont vides
# Quitte avec un avertissement si ce n'est pas le cas.
if [[ -z $DLw ]] || [[ -z $DLc ]] || [[ -z $ULw ]] || [[ -z $ULc ]] || [[ -z $Loc ]]
then
usage
exit 3
fi
# Vérifier si les arguments maximums de téléchargement et d'envoi sont vides si des données de performance ont été demandées.
if [ "$PerfData" == "TRUE" ]
then
if [[ -z $MaxDL ]] || [[ -z $MaxUL ]]
then
echo "2"
usage
exit 3
fi
fi
# Vérification des arguments non numériques
isnumeric $DLw "Niveau Download Warning"
isnumeric $DLc "Niveau Download Critical"
isnumeric $ULw "Niveau Upload Warning"
isnumeric $ULc "Niveau Upload Critical"
# Vérifier les maximums d'upload et de download uniquement si des données de performance sont demandées.
if [ "$PerfData" == "TRUE" ]; then
isnumeric $MaxDL "Niveau Download Maximum "
isnumeric $MaxUL "Niveau Upload Maximum"
fi
# Vérifier si le binaire bc et jq sont installés
type bc >/dev/null 2>&1 || { echo >&2 "${red}Veuillez installer bc binary (pour effectuer des opérations en virgule flottante)${nc}"; exit 3; }
type jq >/dev/null 2>&1 || { echo >&2 "${red}Veuillez installer jq binary (pour l'analyse du json)${nc}"; exit 3; }
# Vérifier que les niveaux d'alerte ne sont pas inférieurs aux niveaux critiques
if float_cond "$DLw < $DLc"; then
echo "${red} \$DLw est inférieur à \$DLc !${nc}"
usage
exit 3
elif float_cond "$ULw < $ULc"; then
echo "${red} \$ULw est inférieur à \$ULc ! ${nc}"
usage
exit 3
fi
# Arguments de sortie pour le débogage
if [ "$debug" == "TRUE" ]; then
echo "${yellow}*-*-*-*-*-*-*-*-*-*-"
echo "* DEBUG MODE"
echo "*-*-*-*-*-*-*-*-*-*-${nc}"
echo "Download Warning Level = ${green}"$DLw${nc}
echo "Download Critical Level = ${green}"$DLc${nc}
echo "Upload Warning Level = ${green}"$ULw${nc}
echo "Upload Critical Level = ${green}"$ULc${nc}
echo "Server Location = ${green}"$Loc${nc}
fi
# Configurer la commande en fonction du choix d'un serveur cible automatique ou non
if [ "$Loc" == "a" ]; then
if [ "$debug" == "TRUE" ]; then
echo " Mode automatique"
fi
command=$($STb/speedtest --unit GB/s --format=json --accept-license --accept-gdpr)
else
if [ "$debug" == "TRUE" ]; then
echo " Avec un serveur cible definie"
fi
command=$($STb/speedtest --server-id=$Loc --unit GB/s --format=json --accept-license --accept-gdpr)
fi
#
typeset -a array
array=($command)
# Definition des fichiers de travail
speedtest_tempfile="/tmp/speedtest-tmp.json"
speedtest_file="/tmp/speedtest.json"
# Sauvegarde du fichier temporaire
cat <<EOF > ${speedtest_tempfile}
${array[@]}
EOF
# Mise en format json
good=$(cat ${speedtest_tempfile} | jq .)
# Sauvegarde du fichier final
cat <<EOF > ${speedtest_file}
${good}
EOF
#
typeset -a reply_JITTER
typeset -a reply_LATENCY
typeset -a reply_LOW
typeset -a reply_HIGH
typeset -a reply_DOWNLOAD_BANDWIDTH
typeset -a reply_UPLOAD_BANDWIDTH
typeset -a reply_PACKETLOSS
# Récupération de variable dans le fichiers json
JITTER=$(cat ${speedtest_file} | grep jitter | cut -f2 -d":" | sed 's/,/\n/g' | head -n 1 | cut -c 2- )
LATENCY=$(cat ${speedtest_file} | grep latency | cut -f2 -d":" | sed 's/,/\n/g' | head -n 1 | cut -c 2- )
LOW=$(cat ${speedtest_file} | grep low | cut -f2 -d":" | sed 's/,/\n/g' | head -n 1 | cut -c 2- )
HIGH=$(cat ${speedtest_file} | grep high | cut -f2 -d":" | sed 's/,/\n/g' | head -n 1 | cut -c 2- )
DOWNLOAD_BANDWIDTH_tmp=$(cat ${speedtest_file} | grep bandwidth | cut -f2 -d":" | sed 's/,/\n/g' | head -n 1 | cut -c 2- )
UPLOAD_BANDWIDTH_tmp=$(cat ${speedtest_file} | grep bandwidth | cut -f2 -d":" | sed 's/,/\n/g' | sed -n '3 p' | cut -c 2- )
PACKETLOSS=$(cat ${speedtest_file} | grep packetLoss | cut -f2 -d":" | sed 's/,/\n/g' | head -n 1 | cut -c 2- )
ISP=$(cat ${speedtest_file} | grep isp | cut -f2 -d":" | sed 's/,/\n/g ; s/"//g' | head -n 1 | cut -c 2- )
EXTERNALIP=$(cat ${speedtest_file} | grep externalIp | cut -f2 -d":" | sed 's/,/\n/g ; s/"//g' | head -n 1 | cut -c 2- )
HOST=$(cat ${speedtest_file} | grep host | cut -f2 -d":" | sed 's/,/\n/g ; s/"//g' | head -n 1 | cut -c 2- )
NAME=$(cat ${speedtest_file} | grep name | cut -f2 -d":" | sed 's/,/\n/g ; s/"//g' | head -n 3 | sed -n '3 p' | cut -c 2- )
LOCATION=$(cat ${speedtest_file} | grep location | cut -f2 -d":" | sed 's/,/\n/g ; s/"//g' | head -n 1 | cut -c 2- )
COUNTRY=$(cat ${speedtest_file} | grep country | cut -f2 -d":" | sed 's/,/\n/g ; s/"//g' | head -n 1 | cut -c 2- )
IPHOST=$(cat ${speedtest_file} | grep ip | cut -f2 -d":" | sed 's/,/\n/g ; s/"//g' | head -n 1 | cut -c 2- )
# Convertion de la valeur
valeur="0.000008"
DOWNLOAD_BANDWIDTH=$(echo "${DOWNLOAD_BANDWIDTH_tmp[0]}*${valeur}/1" | bc)
UPLOAD_BANDWIDTH=$(echo "${UPLOAD_BANDWIDTH_tmp[0]}*${valeur}/1" | bc)
#
if [ "$debug" == "TRUE" ]; then
echo "${yellow}*-*-*-*-*-*-*-*-*-*-"
echo "* DEBUG MODE"
echo "*-*-*-*-*-*-*-*-*-*-${nc}"
echo "Ping"
echo "Jitter = ${green}${JITTER[0]}${nc}"
echo "Latency = ${green}${LATENCY[0]}${nc}"
echo "Low = ${green}${LOW[0]}${nc}"
echo "High = ${green}${HIGH[0]}${nc}"
echo "Download"
echo "Download bandwidth = ${green}${DOWNLOAD_BANDWIDTH}${nc}"
echo "Upload"
echo "Upload bandwidth = ${green}${UPLOAD_BANDWIDTH}${nc}"
echo "PacketLoss = ${green}${PACKETLOSS[0]}${nc}"
echo "information"
echo "ISP = ${green}${ISP[0]}${nc}"
echo "EXTERNAL IP = ${green}${EXTERNALIP[0]}${nc}"
echo "Host = ${green}${HOST[0]}${nc}"
echo "Name = ${green}${NAME[0]}${nc}"
echo "Location = ${green}${LOCATION[0]}${nc}"
echo "Country = ${green}${COUNTRY[0]}${nc}"
echo "IP HOST = ${green}${IPHOST[0]}${nc}"
fi
# Variables unité pour affichage
pingUOM="ms"
downloadUOM="Mbit/s"
uploadUOM="Mbit/s"
rm -f ${speedtest_tempfile}
rm -f ${speedtest_file}
# Configurer les variables de statut et de code de sortie
status=
code=
# Nous vérifions maintenant si les valeurs renvoyées se situent dans les fourchettes définies.
if float_cond "$download < $DLc"; then
if [ "$debug" == "TRUE" ]; then
echo "${yellow}*-*-*-*-*-*-*-*-*-*-"
echo "* DEBUG MODE"
echo "*-*-*-*-*-*-*-*-*-*-${nc}"
echo "Télécharger moins que la limite critique. ${green}${download}${nc} = ${green}${download}${nc} et ${green}${DLc} = ${green}${DLc}${nc} "
fi
status="CRITICAL"
code=2
elif float_cond "$upload < $ULc"; then
if [ "$debug" == "TRUE" ]; then
echo "${yellow}*-*-*-*-*-*-*-*-*-*-"
echo "* DEBUG MODE"
echo "*-*-*-*-*-*-*-*-*-*-${nc}"
echo "Upload inférieur à la limite critique. ${green}${upload}${nc} = ${green}${upload}${nc} et ${green}${ULc}${nc} = ${green}${ULc}${nc}"
fi
status="CRITICAL"
code=2
elif float_cond "$download < $DLw"; then
if [ "$debug" == "TRUE" ]; then
echo "${yellow}*-*-*-*-*-*-*-*-*-*-"
echo "* DEBUG MODE"
echo "*-*-*-*-*-*-*-*-*-*-${nc}"
echo "Téléchargement inférieur à la limite d'avertissement. ${green}${download}${nc} = ${green}${download}${nc} et ${green}${DLw}${nc} = ${green}${DLw}${nc}"
fi
status="WARNING"
code=1
elif float_cond "$upload < $ULw"; then
if [ "$debug" == "TRUE" ]; then
echo "${yellow}*-*-*-*-*-*-*-*-*-*-"
echo "* DEBUG MODE"
echo "*-*-*-*-*-*-*-*-*-*-${nc}"
echo "Upload inférieur à la limite d'avertissement. ${green}${upload}${nc} = ${green}${upload}${nc} et ${green}${ULw}${nc} = ${green}${ULw}${nc}"
fi
status="WARNING"
code=1
else
if [ "$debug" == "TRUE" ]; then
echo "${yellow}*-*-*-*-*-*-*-*-*-*-"
echo "* DEBUG MODE"
echo "*-*-*-*-*-*-*-*-*-*-${nc}"
echo "Tout est correct !"
fi
status="OK"
code=0
fi
out="$status - Ping = ${LATENCY[0]} $pingUOM Paquet perdu = ${PACKETLOSS[0]} Download = ${DOWNLOAD_BANDWIDTH[0]} $downloadUOM Upload = ${UPLOAD_BANDWIDTH[0]} $uploadUOM"
# append perfout if argument was passed to script
if [ "$PerfData" == "TRUE" ]; then
if [ "$debug" == "TRUE" ]; then
echo "${yellow}*-*-*-*-*-*-*-*-*-*-"
echo "* DEBUG MODE"
echo "*-*-*-*-*-*-*-*-*-*-${nc}"
echo "PerfDonnees demandees !"
fi
perfout="|'latency'=${LATENCY[0]} 'packetloss'=${PACKETLOSS[0]} 'download'=${DOWNLOAD_BANDWIDTH[0]};${DLw};${DLc};0;$(echo $MaxDL*1.05|bc) 'upload'=${UPLOAD_BANDWIDTH[0]};$ULw;$ULc;0;$(echo $MaxUL*1.05|bc)"
out=$out$perfout
fi
echo $out
exit $code

54
SpeedTest/README.md Normal file
View File

@ -0,0 +1,54 @@
# Centreon (or Nagios) Plugin for the speedtest
![picture](https://www.tips-of-mine.fr/wp-content/uploads/2023/05/centreon-speedtest.jpg)
probe to extract a large amount of information to validate the internet bandwidth.
## Installation
- Copy the script in the ***"/usr/lib/centreon/plugin"*** folder
#### Installation of the speedtest
- Download the source on its website : https://install.speedtest.net/app/cli/ookla-speedtest-1.2.0-linux-x86_64.tgz
- Positioned the source here: ***"/usr/lib/centreon/plugin/speedtest/"***
<br />
- Identify your reference server
`./speedtest -L`
## Usage
+ Usage `./Check-SpeedTest.sh -c 700 -w 800 -C 100 -W 250 -l 28073 -p TRUE -m 1000 -M 300` (normal mode)
+ Usage `./Check-SpeedTest.sh -c 700 -w 800 -C 100 -W 250 -l a -p TRUE -m 1000 -M 300` (automatic mode)
<br />
+ ***-h***
Display this message
+ ***-w***
Download Warning Level
+ ***-c***
Upload Warning level
+ ***-W***
Warning level of the Upload
+ ***-C***
Upload Crtique alert level
+ ***-l***
Location of the speedtest server
+ ***-p***
Output performance data
+ ***-m***
Maximum Download Level
+ ***-M***
Upload Level Maximum
+ ***-v***
show the version of the plugin
+ ***-V***
Debugging information for tests
## Centreon
![picture](https://www.tips-of-mine.fr/wp-content/uploads/2023/05/2023-05-14-14_57_03-Centreon-IT-Network-Monitoring-%E2%80%94-Mozilla-Firefox.png)
## More info
- more information on the website [Tips-Of-Mine](https://www.tips-of-mine.fr/?p=1837)
## Buy me a coffe
<a href='https://ko-fi.com/R5R2KNI3N' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://storage.ko-fi.com/cdn/kofi4.png?v=3' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>

3
debug.log Normal file
View File

@ -0,0 +1,3 @@
[0703/201232.419:ERROR:registration_protocol_win.cc(107)] CreateFile: Le fichier spécifié est introuvable. (0x2)
[0703/201232.736:ERROR:registration_protocol_win.cc(107)] CreateFile: Le fichier spécifié est introuvable. (0x2)
[0703/201233.088:ERROR:registration_protocol_win.cc(107)] CreateFile: Le fichier spécifié est introuvable. (0x2)