first commit

This commit is contained in:
3err0 2019-06-22 21:07:44 +08:00
commit b8fa300676
6 changed files with 237 additions and 0 deletions

6
config.py Normal file
View File

@ -0,0 +1,6 @@
bot_token=''
proxy = 'socks5h://socks:pr0xy@109.234.36.187:1080'
zabbix_api = 'http://127.0.0.1/api_jsonrpc.php'
zabbix_user = 'api'
zabbix_pass = 'pass'
users = ['1234', '5678']

2
hosts.csv Normal file
View File

@ -0,0 +1,2 @@
IP,Name,Group,Template,Port
10.1.1.1,test0-0-0 000000000000000,AntMiner L3,AntMiner L3,4028
1 IP Name Group Template Port
2 10.1.1.1 test0-0-0 000000000000000 AntMiner L3 AntMiner L3 4028

37
importer.py Normal file
View File

@ -0,0 +1,37 @@
from loadcsv import LoadCSV
from zabbixhost import ZabbixAPI
class Importer:
def __init__(self, filename, user, password, url):
self.hostlist = LoadCSV(filename).export()
self.zabbix = ZabbixAPI(user, password, url)
self.zabbix.login()
def debug(self):
print(self.hostlist)
for line in self.hostlist:
print(line['Template'].split(','))
print(line['Group'])
print(line['Name'])
print(line['IP'])
def chk_ip(self, ip_str):
sep = ip_str.split('.')
if len(sep) != 4:
return False
for i, x in enumerate(sep):
try:
int_x = int(x)
if int_x < 0 or int_x > 255:
return False
except ValueError as e:
return False
return True
def create_host(self):
for line in self.hostlist:
if self.chk_ip(line['IP']) is False:
continue
self.zabbix.get_template_id(line['Template'].split(','))
self.zabbix.get_group_id(line['Group'])
self.zabbix.create_host(line['Name'], line['IP'], line['Port'])

12
loadcsv.py Normal file
View File

@ -0,0 +1,12 @@
import csv
class LoadCSV:
def __init__(self, filename):
self.hostlist = []
with open(filename, newline='', encoding='UTF-8-sig') as f:
f_csv = csv.DictReader(f)
for row in f_csv:
self.hostlist.append(row)
def export(self):
return self.hostlist

63
main.py Normal file
View File

@ -0,0 +1,63 @@
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
#import logging
import config
import telebot
from telebot import apihelper, types
from importer import Importer
apihelper.proxy = {'https': config.proxy}
bot = telebot.TeleBot(config.bot_token)
#logger = telebot.logger
#telebot.logger.setLevel(logging.DEBUG)
def check_permission(uid):
user = str(uid)
for userid in config.users:
if userid == user:
return True
return False
def file_ext(filename):
return filename.split(".")[-1]
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
bot.reply_to(message, "Я тупая машина, и я ничего не умею")
@bot.message_handler(func=lambda message: True)
def echo_message(message):
bot.reply_to(message, message.text)
@bot.message_handler(content_types=['document'])
def handle_file(message):
try:
if check_permission(message.from_user.id):
file_info = bot.get_file(message.document.file_id)
downloaded_file = bot.download_file(file_info.file_path)
if file_ext(message.document.file_name) == 'csv':
src='/media/'+message.document.file_name;
with open(src, 'wb') as new_file:
new_file.write(downloaded_file)
bot.reply_to(message,"Added\n"+src)
imp = Importer(src, config.zabbix_user, config.zabbix_pass, config.zabbix_api)
imp.create_host()
bot.reply_to(message, imp.debug)
else:
bot.reply_to(message, "What is it?")
else:
bot.send_message(message.chat.id, 'Тебе сюда нельзя. Твой ID: ' + str(message.chat.id))
except Exception as e:
bot.reply_to(message,e )
#while True:
# try:
# bot.polling(none_stop=True, interval=0, timeout=10)
# except Exception as e:
# print(e)
# time.sleep(15)
bot.polling(none_stop=True, interval=0, timeout=10)

117
zabbixhost.py Normal file
View File

@ -0,0 +1,117 @@
import requests
import json
class ZabbixAPI:
def __init__(self, user, password, zabbix_url):
# Zabbix URL
self.zabbix_url = zabbix_url
self.header = {"Content-Type": "application/json"}
# login information
self.user = user
self.password = password
self.auth = ""
self.templates_id = []
self.groups_id = []
def login(self):
# Parameter for zabbix API
parameter = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.user,
"password": self.password
},
"id": 1,
"auth": None
})
# Get response text from zabbix API by using POST
response = requests.post(self.zabbix_url, parameter, headers=self.header).text
# Get key from response text
try:
self.auth = json.loads(response)['result']
except KeyError:
print("Login failed")
print("Login Success")
print(self.auth)
def get_template_id(self, templates):
# Init variable for templates_id in list
self.templates_id = []
# Parameter for Get TemplateID in Zabbix API
parameter = json.dumps({
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"host": templates
}
},
"auth": self.auth,
"id": 1
})
# Get response text from zabbix API by using POST
response = requests.post(self.zabbix_url, parameter, headers=self.header).text
# Append list templates_id from response text
for i in json.loads(response)['result']:
self.templates_id.append(str(i['templateid']))
print(self.templates_id)
def get_group_id(self, groups):
# Init variable for groups_id in list
self.groups_id = []
# Parameter for Get GroupID in Zabbix API
parameter = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": groups
}
},
"auth": self.auth,
"id": 1
})
# Get response text from zabbix API by using POST
response = requests.post(self.zabbix_url, parameter, headers=self.header).text
# Append list templates_id from response text
for i in json.loads(response)['result']:
self.groups_id.append(str(i['groupid']))
print(self.groups_id)
def create_host(self, hostname, interface_ip, interface_port):
# Put the group ID and template ID into dict
group = []
template = []
for ids in self.groups_id:
group.append({"groupid": str(ids)})
for ids in self.templates_id:
template.append({"templateid": str(ids)})
# Parameter for CreateHost in Zabbix API
parameter = json.dumps({
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": interface_ip,
"name": hostname,
"interfaces": [{
"type": 1,
"main": 1,
"useip": 1,
"ip": interface_ip,
"dns": "",
"port": interface_port
}],
"groups": group,
"templates": template
},
"auth": self.auth,
"id": 1
})
# Create host with zabbix API by using POST
response = requests.post(self.zabbix_url, parameter, headers=self.header).text
print(response)