Esempio n. 1
0
def relogin():
    try:
        _test = client.current_period
    except:
        if client.login(
                env_file.get(path='.env')['USERNAME'],
                env_file.get(path='.env')['PASSWORD']):
            print("Re-Login Successful")
        else:
            print("Re-Login Error !")

    #client.login()
    return
Esempio n. 2
0
 def tenor(self, query):
     token = env_file.get()
     gif_object = requests.get(
         f"https://api.tenor.com/v1/search?q={query}&key={token['TENOR_KEY']}&limit=50"
     ).json()
     choice = random.choice(range(50))
     url = gif_object["results"][choice]["media"][0]["gif"]["url"]
     return url
def get_netbox_devices():
    nb_env = env_file.get(path='env-netbox')
    nb = pynetbox.api(url=nb_env['NETBOX_API_URL'],
                      token=nb_env['NETBOX_API_KEY'],
                      ssl_verify=False)

    all_devices = nb.dcim.devices.all()
    return all_devices
Esempio n. 4
0
def ssh_session(ip):
    #This establishes the SSH session using Netmiko
    ssh_creds = env_file.get(path="env/ssh")
    netmiko_creds = {
        "device_type": "cisco_ios",
        "ip": ip,
        "username": ssh_creds["SSH_USERNAME"],
        "password": ssh_creds["SSH_PASSWORD"],
        "secret": ssh_creds["SSH_SECRET"]
    }

    netmiko_session = Netmiko(**netmiko_creds)
    netmiko_session.enable()
    return netmiko_session
Esempio n. 5
0
def run():
    """
    Bot setup
    """
    token = env_file.get()
    bot.add_cog(DevCommands(bot))
    bot.add_cog(GeneralCommands(bot))
    bot.add_cog(LinksCommands(bot))
    if 'DBL_TOKEN' in token:
        bot.add_cog(TopGG(bot, token['DBL_TOKEN']))
    if 'WEBHOOK_URL' in token:
        logs.webhook_url = token['WEBHOOK_URL']
    if 'WEBHOOK_ERROR_SUPERVISOR_ID' in token:
        logs.error_supervisor = token['WEBHOOK_ERROR_SUPERVISOR_ID']
    bot.run(token["BOT_TOKEN"])
async def run():
    """
    Bot setup
    """
    async with aiohttp.ClientSession() as session:
        token = env_file.get()
        bot.add_cog(DevCommands(bot))
        bot.add_cog(GeneralCommands(bot, session))
        bot.add_cog(LinksCommands(bot))
        if 'DBL_TOKEN' in token:
            bot.add_cog(TopGG(bot, token['DBL_TOKEN']))
        if 'WEBHOOK_URL' in token:
            logs.webhook_url = token['WEBHOOK_URL']
        if 'WEBHOOK_ERROR_SUPERVISOR_ID' in token:
            logs.error_supervisor = token['WEBHOOK_ERROR_SUPERVISOR_ID']
        await bot.start(token['BOT_TOKEN'])
Esempio n. 7
0
    def __init__(self, ip, port=22, device_type="cisco_xr"):
        self.ip = ip
        self.port = port
        self.device_type = device_type
        self.creds = env_file.get(path="env/netmiko")

        self.netmiko_creds = {
            "ip": self.ip,
            "port": self.port,
            "device_type": self.device_type,
            "username": self.creds["SSH_USERNAME"],
            "password": self.creds["SSH_PASSWORD"],
            "secret": self.creds["SSH_SECRET"]
        }

        self.ssh_session = None
Esempio n. 8
0
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

        self.env_creds = env_file.get(path="env\ssh")

        self.ssh_details = {
            "device_type": "cisco_ios",
            "ip": self.ip,
            "port": self.port,
            "username": self.env_creds["SSH_USERNAME"],
            "password": self.env_creds["SSH_PASSWORD"],
            "secret": self.env_creds["SSH_SECRET"]
        }

        self.ssh_session = Netmiko(**self.ssh_details)
        self.ssh_session.enable()
Esempio n. 9
0
def _cli(env_path, apps):
    for app in apps:
        path = os.path.join(app, "Contents", "Info.plist")
        data = mac_app_env.plist.read(path)
        data["LSEnvironment"] = env_file.get(env_path)
        mac_app_env.plist.write(path, data)
Esempio n. 10
0
            if self.game == None:
                ids = self.seekUsers(
                    ["Satsuwu#4597", message.author, "Knowle#3321"])
                self.game = Poker([Player(x) for x in ids])
                self.game.start()
                for player in self.game.players:
                    image = discord.File(
                        self.drawing.draw(player.cards, player.id.id))
                    await player.id.send("Those are your cards", file=image)
            else:
                await message.channel.send("A game is already in progress")
        elif message.content == '#pass' or message.content == '#next':
            if self.game != None:
                result = self.game.next()
                if result == None:
                    image = discord.File(
                        self.drawing.draw(self.game.tableCards))
                    await message.channel.send("Current table cards",
                                               file=image)
                else:
                    await message.channel.send(
                        "The winners are: " +
                        ", ".join([str(p.id) for p in result]))
                    self.game = None
            else:
                await message.channel.send("There is no game in progress")


enviroment = env_file.get()
client = MyClient()
client.run(enviroment.get("DISCORD_TOKEN"))
Esempio n. 11
0
# -*- coding: utf-8 -*-
import env_file
import pronotepy
import datetime
import html
import pickle

client = pronotepy.Client(
    'https://0060013g.index-education.net/pronote/eleve.html?login=true')
if client.login(
        env_file.get(path='.env')['USERNAME'],
        env_file.get(path='.env')['PASSWORD']):
    print("Login Successful")

homework_backup = {}
profs_backup = {}
manual_add_list = {}


def save_obj(obj, name):
    with open('obj/' + name + '.pkl', 'wb') as f:
        pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)


def load_obj(name):
    with open('obj/' + name + '.pkl', 'rb') as f:
        return pickle.load(f)


def yes_or_no(boolean: bool):
    if boolean:
Esempio n. 12
0
import discord
from discord.ext import commands
import env_file
import database
from PIL import Image, ImageDraw, ImageFont
import io
import aiohttp

token = env_file.get()


class JoinLeave(commands.Cog, name="Poll"):
    def __init__(self, client):
        self.client = client

    async def make_join_leave_image(self, image_url, header, subtitle):
        async with aiohttp.ClientSession() as session:
            async with session.get(str(image_url)) as resp:
                image_bytes = await resp.read()
        profile_pic = Image.open(io.BytesIO(image_bytes), "r")
        profile_pic = profile_pic.resize((160, 160), Image.ANTIALIAS)
        background = Image.open("assets/background.jpg", "r")
        font_1 = ImageFont.truetype("assets/DiscordFont.otf", 50)
        font_2 = ImageFont.truetype("assets/DiscordFont.otf", 45)
        bigsize = (profile_pic.size[0] * 3, profile_pic.size[1] * 3)
        mask = Image.new("L", bigsize, 0)
        draw = ImageDraw.Draw(mask)
        draw.ellipse((0, 0) + bigsize, fill=255)
        mask = mask.resize(profile_pic.size, Image.ANTIALIAS)
        profile_pic.putalpha(mask)
        background.paste(profile_pic, (350, 280), profile_pic)
Esempio n. 13
0
def _cli(plist_file, env_files):
    vars = dict(launchd_env.read(plist_file))
    for f in env_files:
        vars.update(env_file.get(f))
    launchd_env.write(plist_file, **vars)
Esempio n. 14
0
#!/usr/bin/env python
import env_file
import os

os.chdir(os.path.dirname(__file__))

data = env_file.get()
print(data)

assert data["PGDATA"] == "/var/lib/postgresql/data"
assert data["POSTGRES_USER"] == "postgres"

assert 'COMMENT' not in data
assert data["SINGLE_QUOTED"] == "value"
assert data["DOUBLE_QUOTED"] == "value"
assert data["EXPORTED"] == "value"
assert data["CONTAINS_EXPORT"] == "key=value; export more"
Esempio n. 15
0
from ncclient import manager
import env_file

credentials = env_file.get(path="env/netmiko")

m = manager.connect(host="192.0.2.1",
                    username=credentials["SSH_USERNAME"],
                    password=credentials["SSH_PASSWORD"],
                    hostkey_verify=False,
                    look_for_keys=False)

for x in m.server_capabilities:
    print(x)

print(m.get_schema('ietf-interfaces'))
print(m.get_config(source='running'))
Esempio n. 16
0
from excel_loader import ExcelLoader
import env_file
import sys
from pymongo import MongoClient
from bson.objectid import ObjectId
from customer import HealthEntity

ENV = env_file.get(path='.env-' + sys.argv[1])

mongoClient = MongoClient(ENV['MONGO_URL'])

db = mongoClient.prepaid

customers_collenction = db.health_entities

customerLoader = ExcelLoader(ENV['BASE'])

ws = customerLoader.sheet('BASE COMPLETA')

rows = list(ws.iter_rows())[3:]


def map_customer_to_mongo(pr):
    mongo_practice = pr.to_dic()
    mongo_practice['_id'] = str(ObjectId())
    return mongo_practice


def parseList(value):
    return value
Esempio n. 17
0
import env_file

import parse_data
import web_scrapper

if __name__ == "__main__":

    base_url = env_file.get(path='.env')['BASE_URL']
    initial_url = env_file.get(path='.env')['INITIAL_URL']
    duration_wait = int(env_file.get(path='.env')['DURATION'])
    file_name = env_file.get(path='.env')['FILE_NAME']
    limit_record = int(env_file.get(path='.env')['LIMIT_RECORD'])

    scrapper = web_scrapper.WebScrapper(base_url, initial_url, duration_wait,
                                        file_name, limit_record)
    scrapper.startScrapper()

    perform_analysis = parse_data.ParseData('productData.json')
    perform_analysis.PerformAnalysis()
Esempio n. 18
0
import env_file
from facebook_scraper import get_posts
from tinydb import Query, TinyDB

import telegram

MAX_TELEGRAM_MSG_LEN = 900

# initialization
envs = env_file.get()
db = TinyDB('./db.json')

page_name = envs['PAGE_NAME']


def get_new_posts():
    '''
    Retrieves the last 2 pages of posts and checks if there is are new posts (not already in DB).
    If new posts are found they're returned with newest at the bottom.
    '''
    new_posts = list()
    Post = Query()  # Database Post object

    # Retrieve last 2 pages of posts
    facebook_posts = get_posts(page_name, pages=2)

    for post in facebook_posts:
        # Check if it has already been posted
        if(len(db.search(Post.post_id == post['post_id'])) == 0):
            new_posts.append(post)
Esempio n. 19
0
import env_file
from discord import Embed
from discord.ext import commands

from .helper import *

# Import cogs
from vandybot.dining import Dining
from vandybot.hours import Hours

PREFIX = "~"
bot = commands.Bot(command_prefix=commands.when_mentioned_or(PREFIX),
                   case_insensitive=True)

# Read tokens
tokens = env_file.get()
DEBUGGING = tokens.get("DEBUGGING", "False") == "True"
DEBUG_GUILD_ID = int(tokens.get("DEBUG_GUILD_ID", "0"))

TOKEN = tokens.get("BOT_TOKEN")
if DEBUGGING:
    TOKEN = tokens.get("DEBUG_BOT_TOKEN", TOKEN)


@bot.event
async def on_ready():
    print("VandyBot has connected. Awaiting command requests...")
    text = DEFAULT_TEXT if not DEBUGGING else "Currently undergoing maintenance"
    await bot.change_presence(activity=presence(text))

Esempio n. 20
0
                          color=color)
    embed.add_field(name="Pour le :", value=f"**{date}**", inline=True)
    embed.add_field(name="Professeur :", value=f"**{prof}**", inline=True)

    await channel.send(embed=embed)


async def embed_profs(absence, channel):
    if absence[4] in BLUE_LABEL:
        embed = discord.Embed(title=absence[4],
                              description=f"**{absence[1]}**",
                              color=0x0000ff)
    elif absence[4] in RED_LABEL:
        embed = discord.Embed(title=absence[4],
                              description=f"**{absence[1]}**",
                              color=0xff0000)
    else:
        embed = discord.Embed(title=absence[4],
                              description=f"**{absence[1]}**",
                              color=0x808080)
    embed.add_field(name="Matière :", value=f"**{absence[0]}**", inline=True)
    embed.add_field(name="Date :", value=f"**{absence[2]}**", inline=True)
    embed.set_thumbnail(
        url=
        "https://www.cat-catounette.com/wp-content/uploads/2017/07/warning-icon-24-1024x1024.png"
    )
    await channel.send(embed=embed)


client.run(env_file.get(path='.env')['TOKEN'])
Esempio n. 21
0
import mysql.connector
import env_file

env = env_file.get()

db = mysql.connector.connect(
    host=env["MYSQL_HOST"],
    user=env["MYSQL_USER"],
    password=env["MYSQL_PW"],
    database=env["MYSQL_DB"],
)
db.set_charset_collation('utf8mb4', 'utf8mb4_general_ci')

cursor = db.cursor(buffered=True)
cursor.execute("DROP TABLE IF EXISTS mobilizations")
cursor.execute("CREATE TABLE mobilizations ( \
	src_subreddit_name VARCHAR(15), \
	src_post_name VARCHAR(15) PRIMARY KEY, \
	src_post_author VARCHAR(15), \
	tgt_subreddit_name VARCHAR(15), \
	tgt_post_name VARCHAR(15), \
	tgt_post_author VARCHAR(15), \
	n_comments_by_src_memb_before INT, \
	n_comments_by_src_memb_after INT, \
	before_after_ratio DOUBLE, \
	INDEX(src_subreddit_name), \
	INDEX(src_post_author), \
	INDEX(tgt_subreddit_name), \
	INDEX(tgt_post_name), \
	INDEX(tgt_post_author) \
	) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci")
import os
import env_file

ENV = env_file.get(path='.env')

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ENV['SECRET_KEY']

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'User',
    'MailSendgrid',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
import env_file
import json
import time
import re
from netmiko import ConnectHandler

device_details = env_file.get(path="env/ssh")

device = ConnectHandler(
    **{
        "device_type": "cisco_xr",
        "ip": device_details["DEVICE"],
        "username": device_details["USERNAME"],
        "password": device_details["PASSWORD"]
    })

command = "show interfaces brief"

output = device.send_command(command)
device.disconnect()

time_start = time.time()

interfaces = []

named_groups = [
    "interface", "state", "line_state", "encapsulation", "mtu", "bandwidth"
]
interface_pattern = r"^\s+(?P<{}>\S+)\s+(?P<{}>up|down|admin-down)\s+(?P<{}>up|down|admin-down)\s+(?P<{}>\S+)\s+(?P<{}>\d+)\s+(?P<{}>\d+)$$".format(
    *named_groups)
Esempio n. 24
0
def _cli(env_path, plist_paths):
    for plist_path in plist_paths:
        data = launchd_env.plist.read(plist_path)
        data["EnvironmentVariables"] = env_file.get(env_path)
        launchd_env.plist.write(plist_path, data)
def connect_nb():
    netbox_creds = env_file.get(path="env/netbox")
    nb = pynetbox.api(netbox_creds["NETBOX_URL"],
                      token=netbox_creds["NETBOX_KEY"])
    return nb
Esempio n. 26
0
A simply POST request is sent to some predefined Flask routes (sdncontroller) with 0 validation...
"""


def message_parser(line):
    temp_message = None
    try:
        temp_message = json.loads(line)
    except Exception as error:
        logging.debug("Error trying json.loads() on line: \n{}".format(line))
        logging.debug("Exception Error was: {}".format(error))
    return temp_message


api_details = env_file.get(path="/exabgp/env/api")
api_url = api_details["flask_api"]

counter = 0
while True:
    try:
        line = stdin.readline().strip()

        if line == "":
            counter += 1
            if counter > 100:
                break
            continue
        counter = 0

        message = message_parser(line)