Exemplo n.º 1
0
def GetData():
    print("-CALLING RASPBERRY PI")

    pihole = ph.PiHole('192.168.0.37')

    url = 'http://192.168.0.37/admin/'
    response = requests.get(url)

    soup = BeautifulSoup(response.content, 'html.parser')

    soup_temp = soup.find('a', id='temperature')
    temp = str(soup_temp.text).replace('Temp:', '').replace('°C', '')
    temp = temp.replace('°C', '')
    temp = temp.replace(' ', '')
    temp = temp.replace(' ', '')

    soup_memory = soup_temp.find_next_siblings()
    memory = list(soup_memory)[3].text
    memory = str(memory).replace('Memory usage:', '')
    memory = str(memory).replace('%', '')
    memory = str(memory).replace(' ', '')
    memory = str(memory).replace(' ', '')
    memory = str(memory).replace(' ', '')

    data_return = [
        pihole.status, pihole.ads_percentage, pihole.blocked,
        pihole.gravity_last_updated['relative']['days'],
        pihole.gravity_last_updated['relative']['hours'], temp, memory
    ]

    return data_return
 def set_server(self, server):
     if self.__running:
         print("Please stop the script before running.")
     else:
         try:
             self.__pihole_interface = pihole.PiHole(server)
             print("Instantiated new instance of Pi-hole API.")
         except:
             sys.stderr.print("There was a problem while attempting to connect to the specified Pi-hole server.")
Exemplo n.º 3
0
def get_pihole_handle():
    """Connect to PiHole API and return handle."""
    # There should only be 1 entry (the "active" one).  Maybe get the last?
    credentials = PiHoleAdmin.objects.get(pk=1)

    pihole = ph.PiHole(credentials.name)
    pihole.authenticate(credentials.passwd)
    #pihole.refresh()
    #print("DBG: pihole status= ", pihole.status)
    return pihole
Exemplo n.º 4
0
def piholer():
    for ip in ip_list:
        try:
            pihole = ph.PiHole(ip)
            blacklist = pihole.getList("black")
            for burl in blacklist:
                if len(burl) > 0:
                    print('\33[32m[+]Success: {} -> {} domains\33[0m'.format(
                        ip, len(burl)))
                    for i in burl:
                        b_domain.append(i)
        except:
            print('\033[91m[-]Failed {}\033[0m'.format(ip))
            pass
Exemplo n.º 5
0
def queries_thread():
    """Print pihole stats to the lcd"""

    lcd.clear()
    t = threading.currentThread()
    while getattr(t, "running", True):
        pihole = ph.PiHole("192.168.1.32")

        lcd.set_cursor_position(0, 0)
        lcd.write('{} queries'.format(pihole.queries))

        lcd.set_cursor_position(0, 1)
        lcd.write('{}% blocked'.format(pihole.ads_percentage))

        lcd.set_cursor_position(0, 2)
        lcd.write('{} total'.format(pihole.blocked))

        time.sleep(5)
Exemplo n.º 6
0
def run_script(settings, client):
    api = ph.PiHole(settings.pihole_ip)
    api.refresh()
    domains_being_blocked = api.domain_count.replace(",", "")
    dns_queries_today = api.queries.replace(",", "")
    ads_percentage_today = api.ads_percentage
    ads_blocked_today = api.blocked.replace(",", "")
    unique_domains = api.unique_domains.replace(",", "")
    queries_forwarded = api.forwarded.replace(",", "")
    queries_cached = api.cached.replace(",", "")
    clients_ever_seen = api.total_clients.replace(",", "")
    unique_clients = api.unique_clients.replace(",", "")
    status = api.status.capitalize()

    send_msg(settings, client, ads_percentage_today, ads_blocked_today,
             dns_queries_today, domains_being_blocked, unique_domains,
             queries_forwarded, queries_cached, clients_ever_seen,
             unique_clients, status)
Exemplo n.º 7
0
def piholer():
    for ip in ip_list:
        try:
            pihole = ph.PiHole(ip)
            core = pihole.getVersion()['core_current']
            web = pihole.getVersion()['web_current']
            FTL = pihole.getVersion()['FTL_current']
            blacklist = pihole.getList("black")
            content.append('\n\nIP -> {}\ninfo -> Core {} | web {} | FTL {}'.format(ip, core, web, FTL))
            for burl in blacklist:
                if len(burl) > 0 :
                    print('\33[32m[+]Success: {} -> {} domains\33[0m'.format(ip, len(burl)))
                    for i in burl:
                        content.append('   {}'.format(i))

        except:
            print('\033[91m[-]Failed {}\033[0m'.format(ip))
            pass
Exemplo n.º 8
0
def main():
    
    pihole = ph.PiHole("192.168.0.10")
#    print(pihole.status, pihole.domain_count, pihole.queries, pihole.blocked, pihole.ads_percentage,
#pihole.unique_domains, pihole.forwarded, pihole.cached, pihole.total_clients, pihole.unique_clients,
#pihole.total_queries)
    #weather = WEATHER()
    #condition = weather.getCondition()
    #temperature = weather.getTemperature()
    #print (temperature)
    
    weather = WEATHER()
    myAlarms = []
    clock = CLOCK(myAlarms)
    advice = ADVICE()
#    allInput = ALLINPUT(clock, myAlarms, weather)
    
    controller = CONTROLLER(clock, myAlarms, weather, advice, pihole)
    controller.startDisplayView()
Exemplo n.º 9
0
def system_thread():
    """Print system load, memory usage, and temperature to the lcd"""

    lcd.clear()
    t = threading.currentThread()
    while getattr(t, "running", True):
        pihole = ph.PiHole("192.168.1.32")

        one_minute, five_minute, fifteen_minute = [
            x / psutil.cpu_count() * 100 for x in psutil.getloadavg()
        ]
        memory = psutil.virtual_memory()
        temp = psutil.sensors_temperatures(fahrenheit=True)['cpu-thermal'][0]

        lcd.set_cursor_position(0, 0)
        lcd.write('Load {}'.format(one_minute))

        lcd.set_cursor_position(0, 1)
        lcd.write('Memory {}'.format(memory.percent))

        lcd.set_cursor_position(0, 2)
        lcd.write('{} F'.format(temp.current))

        time.sleep(5)
Exemplo n.º 10
0
    piglow.show()
    time.sleep(0.1)


def flash_all():
    flash_red()
    flash_orange()
    flash_yellow()
    flash_green()
    flash_blue()
    flash_white()


# MAIN
# Create an object
pihole = ph.PiHole("10.0.0.2")
status = pihole.status
print("PiHole-PiGlow is " + status)

if status == 'enabled':
    enabled = True
    flash_all()
else:
    enabled = False

# Set the current ad count on startup
ads = get_ads()

system_cycles = 0
while enabled:
Exemplo n.º 11
0
def getInfo(instance, port):
    if domain:
        hostname = '.'.join([instance, domain])
        pihole = ph.PiHole(hostname, port = port)
        blacklist = pihole.getList("black")[1]
        print(blacklist)
Exemplo n.º 12
0
import discord
from discord_slash import cog_ext, SlashContext
import pihole as ph
import asyncio
import os
from discord.ext import commands
from discord_slash.utils.manage_commands import create_option, create_choice
from .modules import sshCmd as sshModule

pihole = ph.PiHole("a")
pihole.authenticate("a")
pihole.refresh()
ip="a"

class Pi(commands.Cog):

    def __init__(self, bot):
        self.bot=bot

    @cog_ext.cog_slash(name="stats", guild_ids=[your serverid], description="Pihole Stats")
    async def stats(self, ctx):
        pihole.refresh()
        osbuild=os.popen("uname -a").read()
        pibuild=os.popen(f"ssh root@{ip} 'uname -a'").read()
        embed=discord.Embed(title="Stats", description=f"```Overall Status: {pihole.status}\nBlocked 😎: {pihole.blocked}\nQueries (Without Blocked 😎): {pihole.queries}\nTotal Queries: {pihole.total_queries}\n\n```", colour=0xFF0000)
        embed.add_field(name="** **", value=f"```Domain Count: {pihole.domain_count}\nUnique Clients/Total Clients: {pihole.unique_clients}/{pihole.total_clients}\n\n```")
        embed.add_field(name="** **", value=f"```Host Build: {osbuild}\nPi Build: {pibuild}```", inline=False)
        await ctx.send(embed=embed)


    @cog_ext.cog_subcommand(base="filter", name="add", guild_ids=[your serverid], description="Adds a domain to the blacklist")
Exemplo n.º 13
0
import epd2in13_V2
import time
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont
import pihole as ph
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-a",
                    type=str,
                    help="IP address of a system running PiHole",
                    default="127.0.0.1")
piholeip = parser.parse_args()

try:
    pihole = ph.PiHole(piholeip.a)
    pihole.refresh()
except OSError:
    print("This IP does not have a PiHole running")
    quit()

epd = epd2in13_V2.EPD()
epd.init(epd.FULL_UPDATE)

x_keys = 0
y_values = 0


def get_data():
    global x_keys
    global y_values
Exemplo n.º 14
0
 def __init__(self, config):
     self.__ph = pihole.PiHole(config['pi-hole']['ip'])
     self.__ph.authenticate(config['pi-hole']['pass'])
     self.__ph.refresh()
     self.__mac_vendors = MacLookup()
     self.__mac_vendors.loop.run_until_complete(self.__mac_vendors.async_lookup.load_vendors())
Exemplo n.º 15
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT

import pihole as ph
from papirus import PapirusTextPos
import configparser

# set up text writer
text = PapirusTextPos(autoUpdate=False)
fontPath = '/usr/share/fonts/opentype/b612/B612-Regular.otf'

# authenticate with the given password
config = configparser.ConfigParser()
config.read('secrets.ini')
pihole = ph.PiHole('localhost')
pihole.authenticate(config['pihole']['password'])

# get top 5 sites
pihole.refresh()
pihole.refreshTop(5)

# display counts
ads = pihole.top_ads
msg = []
for host in ads.keys():
    msg.append(f'{ads[host]:4d} {host}')
    
text.AddText('\n'.join(msg),size=10,fontPath=fontPath)
text.WriteAll()
Exemplo n.º 16
0
from intents.base_intent import BaseIntent
from intents.status_intent import StatusIntent
from intents.enable_intent import EnableIntent
from intents.disable_intent import DisableIntent

sb = SkillBuilder()

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

pihole_server = os.environ['PIHOLE_SERVER']
pihole_images = os.environ['PIHOLE_IMAGES']
pihole_password = os.environ['PIHOLE_PASSWORD']

pihole_client = pihole.PiHole(pihole_server)
pihole_client.authenticate(pihole_password)


def supports_apl(handler_input):

    return handler_input.request_envelope.context.system.device.supported_interfaces.alexa_presentation_apl is not None


def client_refresh(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        pihole_client.refresh()
        return func(*args, **kwargs)

    return wrapper
Exemplo n.º 17
0
# InfluxDB Settings
DB_ADDRESS = os.environ.get('INFLUX_DB_ADDRESS')
DB_PORT = int(os.environ.get('INFLUX_DB_PORT'))
DB_USER = os.environ.get('INFLUX_DB_USER')
DB_PASSWORD = os.environ.get('INFLUX_DB_PASSWORD')
DB_DATABASE = os.environ.get('INFLUX_DB_DATABASE')

# PiHole Settings
PIHOLE_HOSTNAME = str(os.environ.get('PIHOLE_HOSTNAME'))
TEST_INTERVAL = int(os.environ.get('PIHOLE_INTERVAL'))

# Authentication
AUTHENTICATION_TOKEN = os.environ.get('PIHOLE_AUTHENTICATION')

pihole = ph.PiHole(PIHOLE_HOSTNAME)
influxdb_client = InfluxDBClient(DB_ADDRESS, DB_PORT, DB_USER, DB_PASSWORD, None)

def init_db():
    databases = influxdb_client.get_list_database()

    if len(list(filter(lambda x: x['name'] == DB_DATABASE, databases))) == 0:
        influxdb_client.create_database(DB_DATABASE)  # Create if does not exist.
        print('{} - Created database {}'.format(datetime.datetime.now(), DB_DATABASE))
    else:
        # Switch to if does exist.
        influxdb_client.switch_database(DB_DATABASE)
        print('{} - Switched to database {}'.format(datetime.datetime.now(), DB_DATABASE))


def get_data_for_influxdb():
Exemplo n.º 18
0
Usage: 
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""

import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

from gpiozero import CPUTemperature, LoadAverage, DiskUsage

import pihole as ph

pihole = ph.PiHole("192.168.1.13")

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

logger = logging.getLogger(__name__)


# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
    """Send a message when the command /start is issued."""
    bot.send_message(chat_id=update.message.chat_id, text='Hi!')
Exemplo n.º 19
0
ExternalSource = True
HoleStatus = "enabled"

uh.clear()

while True:
    uh.brightness(1)
    if pingOk('216.58.211.163'):

        #PiHole
        PixelNumber = 0
        PixelRow = 0
        uh.set_pixel(PixelNumber, PixelRow, Cr, Cg, Cb)
        uh.show()
        if website_up('http://192.168.11.125/admin/'):
            pihole = ph.PiHole("192.168.11.125")
            pihole.refresh()
            if pihole.status == "enabled":
                uh.set_pixel(PixelNumber, PixelRow, Gr, Gg, Gb)
            else:
                uh.set_pixel(PixelNumber, PixelRow, Rr, Rg, Rb)
            uh.show()
            if not pihole.status == HoleStatus:
                HoleStatus = pihole.status
                exec(open("/usr/local/bin/status_check/inky_update.py").read())
        else:
            uh.set_pixel(PixelNumber, PixelRow, Rr, Rg, Rb)
            uh.show()

        #HomeBridge Admin
        PixelNumber = 1
Exemplo n.º 20
0
#!/usr/bin/env python3

# Import the library
import pihole as ph

pihole = ph.PiHole("192.168.11.125")
pihole.refresh()

pihole.authenticate("poolloop")
pihole.disable(60)

#pihole.refresh()

#print(pihole.status)
#print(pihole.getVersion())
#print(pihole.gravity_last_updated)