/
command_parser.py
84 lines (67 loc) · 2.69 KB
/
command_parser.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
import subprocess
import time
import os
from db import session
from base import Command
from subprocess import STDOUT
"""
Handles the work of validating and processing command input.
"""
def get_valid_commands(queue, fi, file_data):
# TODO: efficiently evaluate commands
# File processing for getting COMMAND LIST and VALID COMMANDS
script_dir = os.path.dirname(__file__)
path = os.path.join(script_dir, fi)
try:
with open(path, "r") as fh:
CommandLine = fh.readlines()
except IOError as err:
CommandLine = file_data
commandList=[]
validList=[]
for line in CommandLine:
if '[COMMAND LIST]' in line:
commandFlag = True
validFlag = False
elif '[VALID COMMANDS]' in line:
commandFlag = False
validFlag = True
if '[COMMAND LIST]' not in line and '[VALID COMMANDS]' not in line and line.rstrip() != '':
if commandFlag :
commandList.append(line.rstrip())
elif validFlag :
validList.append(line.rstrip())
#Get all the valid commands
validCommandsFromInput = set(commandList) & set(validList)
for command in validCommandsFromInput:
try:
try:
start = time.time()
commandResult = subprocess.check_output(command, shell=True, stderr=STDOUT, timeout=60 )
CommandTimeTaken = (time.time() - start)
except subprocess.TimeoutExpired as err:
print('Handling TimeoutExpired: ', err, ' for command: ', command)
CommandTimeTaken = 0 # (if the command takes > 1 minute to complete, mark a 0 which will represent "Not finished")
commandResult = b''
CommandString = command
commandLength = len(command)
print(commandResult)
print(CommandString)
print(commandLength)
print(CommandTimeTaken)
# Check if the commad is already in Table
flag = session.query(Command).filter_by(command_string=CommandString).first()
if flag:
print('Command : "', command, '" is alredy in commands table')
else:
ed_commands = Command(CommandString, commandLength, CommandTimeTaken, commandResult)
session.add(ed_commands)
session.commit()
except subprocess.CalledProcessError as err:
print('Handling CalledProcessError: ', err, ' for command: ', command)
continue
return 200
def process_command_output(queue):
# TODO: run the command and put its data in the db
commandList = session.query(Command).all()
return commandList