-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
executable file
·182 lines (150 loc) · 8.23 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python3
import telebot;
import requests;
import imgkit;
import json;
from telebot import apihelper;
import os, time, datetime, re, sys;
from pprint import pprint
from passwd import webuser, webpass, ipamuser, ipampass, admins, proxy, url, TOKEN, HomeDir, mailuser, mailpasswd
from servicedesk import get_ticket, send_teleg
from search_json import search_vm_json # функция поиска
# check email
from exchangelib import DELEGATE, Account, Credentials
from mailcheck import mailcheck
####
bot = telebot.TeleBot(TOKEN);
apihelper.proxy = proxy
os.popen('stat /proc/1/cmdline') # it's for uptime function
def extract_arg(arg):
return arg.split()[1:]
def get_screen(url):
loginurl = 'https://zabbix.phoenixit.ru/index.php'
logindata = {'autologin' : '1', 'name' : webuser, 'password': webpass, 'enter' : 'Sign in'}
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0', 'Content-type' : 'application/x-www-form-urlencoded'}
session=requests.session()
login=session.post(loginurl, params=logindata, headers=headers)
options = {
'xvfb': ''
}
imgkit.from_string ( session.get(url).text, HomeDir+'out.jpg', css=HomeDir+'/zabbix/dark-theme.css', options=options )
def get_vm_hostname(ip):
try:
token = requests.post('https://ipam.phoenixit.ru/api/apiclient/user/', auth=(ipamuser, ipampass)).json()['data']['token']
headers = {'token':token}
except:
return('Error login in IPAM system, pleas contact to SysAdmin')
try:
search = requests.get(url='https://ipam.phoenixit.ru/api/apiclient/addresses/search/'+ip[0], headers=headers).json()['data'][0]
return('Hostname: '+search['hostname']+', '+' LastSeen: '+search['lastSeen'])
except:
return("No found IP: "+ip[0]+", or error")
@bot.message_handler(commands=['start','help'])
def handle_start_help(message):
pass
@bot.message_handler(content_types=['text'])
def get_text_messages(message):
intext = message.text
print ( "["+str(message.from_user.id)+"]:"+intext )
if message.text.lower() == "id" or message.text.lower() == "/id":
bot.send_message(message.chat.id, "You telegramm ID is:")
bot.send_message(message.chat.id, message.from_user.id)
if str(message.from_user.id) in admins:
if message.text.lower() == "gp" or message.text.lower() == "/gp": #get http url screen
try:
get_screen(url)
except Exception as inst:
#print ( type(inst) ) # the exception instance
#print ( inst.args ) # arguments stored in .args
#print ( inst ) # __str__ allows args to printed directly
#bot.send_message(message.from_user.id, "Error in gen screen, pleas contact to SysAdmin")
pass
try:
foto = open(HomeDir+'out.jpg', 'rb')
bot.send_photo(message.from_user.id, foto)
except:
bot.send_message(message.from_user.id, "Error to send/open image, pleas contact to SysAdmin")
if os.path.exists(HomeDir+'out.jpg'):
os.remove(HomeDir+'out.jpg')
elif re.match( r"^[/]*?ip", intext.lower()):
if re.match( r"^[/]*?ip\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", intext.lower() ): #get ips hostname from IPAM
ip = extract_arg(message.text)
bot.send_message(message.from_user.id, get_vm_hostname(ip))
else:
bot.send_message(message.from_user.id, "IP addres is't correct, please use /ip <192.0.0.1>")
elif intext.lower() == "uptime" or intext.lower() == "/uptime" or intext.lower() == "up" or intext.lower() == "/up":
dateup = os.popen('stat /proc/1/cmdline|grep Change|awk \'{print $2,$3}\'|sed "s/\..........//"|tr -d "\r\n"').read()
up = time.mktime((datetime.datetime.now()).timetuple()) - time.mktime(datetime.datetime.strptime(dateup, "%Y-%m-%d %H:%M:%S").timetuple())
bot.send_message(message.from_user.id, str(datetime.timedelta(seconds=up)) )
elif re.match( r"^[/]*?vm$", intext.lower()):
bot.send_message(message.from_user.id, "Please use:\nvm [-ip <IP>\n|-mac <MAC>\n|-note <NOTE>\n|-name <NAME>\n|-esxi <ESXI>\n|-snap $n]" )
elif re.match( r"^[/]*?vm\s+?-.+", intext.lower()):
args = extract_arg( intext )
argsstr = ' '.join(str(e) for e in args)
search_res = {}
try:
search_res = search_vm_json( argsstr )
except:
bot.send_message(message.from_user.id, "Error to search: "+intext.lower()+", pleas contact to SysAdmin")
if len( search_res ) != 0:
if len( search_res ) < 150:
for key, value in search_res.items():
if re.search( " -all", intext.lower()):
bot.send_message(message.from_user.id, json.dumps( value, sort_keys=True, indent=4) )
else:
path = ""
for k,v in sorted( value['PATH'].items(), reverse=True ):
path = path + "/" + v
#vmres = 'Name: '+value['Name']+'\nStatus: '+value['Status']+'\nNote: '+value['Note']+'\nPath: '+path+'\nguest ip: '+str(value["guest ip"])+'\nguest os: '+value["guest os"]+"\nvcenter: "+value['vcenter']
vmres = 'Name: '+value['Name']+'\nStatus: '+value['Status']+'\nguest ip: '+str(value["guest ip"])
bot.send_message(message.from_user.id, str(vmres) )
else:
bot.send_message(message.from_user.id, "Sorry result is to higth: ["+str(len( search_res ))+"]" )
print ( "Sorry result is to higth: ["+str(len( search_res ))+"]" )
else:
bot.send_message(message.from_user.id, "No result...")
#except:
# bot.send_message(message.from_user.id, "Error to search: "+intext.lower()+", pleas contact to SysAdmin")
elif message.text.lower() == "sd" or message.text.lower() == "/sd":
try:
tickets = get_ticket()
if len(tickets) != 0 :
for key, value in tickets.items():
keyboard = telebot.types.InlineKeyboardMarkup()
keyboard.add(telebot.types.InlineKeyboardButton(text=key, url='https://servicedesk.phoenixit.ru/Task/View/'+key) )
bot.send_message( message.from_user.id, value, reply_markup=keyboard )
else:
bot.send_message( message.from_user.id, "No open tickets." )
except:
text = "Error to get tickets from servicedesk, pleas contact to SysAdmin"
bot.send_message( message.from_user.id, text )
print(text)
# elif intext.lower() == 'kill':
# bot.send_message(message.from_user.id, "Hello! You Kiled me! =( ")
# os.system('kill $PPID')
# quit()
elif intext.lower() == 'cm' or intext.lower() == "/cm":
try:
if str(message.from_user.id) == admins[0]:
newmails = mailcheck(mailuser, mailpasswd, 5)
if len(newmails) != 0:
for mail in newmails:
bot.send_message(message.from_user.id, mail)
else:
bot.send_message(message.from_user.id, "No new mails.")
except:
bot.send_message( message.from_user.id, 'Error to check mail...' )
print(text)
else:
bot.send_message(message.from_user.id, 'For help only put: "/"')
else:
if message.text.lower() != "id" and message.text.lower() != "/id":
bot.send_message(message.chat.id, 'You do\'t have permission!')
#bot.send_sticker(message.chat.id, 'CAADAgADZgkAAnlc4gmfCor5YbYYRAI')
try:
#bot.polling(none_stop=True, interval=0)
bot.polling(none_stop=True, interval=0, timeout=60)
except Exception as inst:
print ( type(inst) ) # the exception instance
print ( inst.args ) # arguments stored in .args
print ( inst ) # __str__ allows args to printed directly