-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetclient.py
169 lines (138 loc) · 5.06 KB
/
netclient.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
import argparse
import logging
import sys
import time
import grpc.framework.interfaces.face
import pyopenconfig.gnmi_pb2 as gnmi_pb2
import gnmi.pkt_pb2 as pkt_pb2
import pyopenconfig.resources
import atexit
from scapy.all import *
from decimal import *
import socket
import requests
# - logging configuration
logging.basicConfig()
logger = logging.getLogger('netclient')
logger.setLevel(logging.DEBUG)
host_ip = "" #h4.IP()
host_port = 9033
mode = "stream"
nums = 0
badsite_keywords= {"twitter", "reddit", "facebook"}
def encodePath(path):
pathStrs = ""
for pe in path:
pstr = pe.name
if pe.key:
for k, v in pe.key.iteritems():
pstr += "[" + str(k) + "=" + str(v) + "]"
pathStrs = pathStrs + "." + pstr
return pathStrs[1:]
def processPacket(response):
for update in response.update.update:
path_metric = encodePath(update.path.elem)
tm = response.update.timestamp
batch = pkt_pb2.IpPairBatch()
update.val.any_val.Unpack(batch)
#print(batch)
badcounter = 0
for pair in batch.ip:
src = pair.src
dst = pair.dest
try:
src_host = socket.getfqdn(src)
except Exception as e:
src_host = "none"
try:
dst_host = socket.getfqdn(dst)
except Exception as e:
dst_host = "none"
#print src_host
#print dst_host
for bad_keyword in badsite_keywords:
if (bad_keyword in src_host or bad_keyword in dst_host):
badcounter=badcounter+1
ptg = float(100)*float(badcounter)/float(len(batch.ip))
print(ptg)
if(ptg>5):
print("DECISION: Back to work!")
decision=True
elif(ptg<=5):
print("DECISION: Keep working...")
decision=False
requests.post('http://localhost:3001/post', json = { 'decision' : decision })
badcounter = 0
# def processSites(ptg):
# if ptg > 5: #value very low.
# backToWork()
# def backToWork(response):
# print "All days are good days, even when they're bad days."
def get(stub, path_str, metadata):
"""Get and echo the response"""
response = stub.Get(pyopenconfig.resources.make_get_request(path_str),
metadata=metadata)
print(response)
def subscribe(stub, path_str, mode, metadata):
logger.info("Client's subscribe method was called.")
global nums
"""Subscribe and echo the stream"""
logger.info("start to subscrib path: %s in %s mode" % (path_str, mode))
subscribe_request = pyopenconfig.resources.make_subscribe_request(path_str=path_str, mode=mode)
#iterator issue
i = 500
try:
for response in stub.Subscribe(subscribe_request, metadata=metadata):
processPacket(response)
i += 500
nums = i
except grpc.framework.interfaces.face.face.AbortionError, error: # pylint: disable=catching-non-exception
if error.code == grpc.StatusCode.OUT_OF_RANGE and error.details == 'EOF':
# https://github.com/grpc/grpc/issues/7192
sys.stderr.write('EOF after %d updates\n' % i)
logger.info('EOF after %d updates\n' % i)
else:
raise
logger.info("Finished streaming, %s updates has been streamed." % i)
def shutdown_hook():
global nums
try:
pass
except Exception:
pass
finally:
logger.info("%s updates has been streamed." % nums)
logger.info('existing program')
def run():
"""Main loop"""
parser = argparse.ArgumentParser()
parser.add_argument('--host', default='localhost',
help='OpenConfig server host') #on mininet host's IP
parser.add_argument('--port', type=int, default=9033,
help='OpenConfig server port')
parser.add_argument('--username', type=str, help='username')
parser.add_argument('--password', type=str, help='password')
parser.add_argument('--mode', type=str, default='stream', help='subscription mode')
parser.add_argument('--debug', type=str, default='on', help='debug level')
group = parser.add_mutually_exclusive_group()
group.add_argument('--get',
help='OpenConfig path to perform a single-shot get')
group.add_argument('--subscribe', type=str, default='interfaces/eth0/ip',
help='OpenConfig path to subscribe to')
args = parser.parse_args()
metadata = None
if args.debug == "off":
logger.setLevel(logging.INFO)
if args.username or args.password:
metadata = [("username", args.username), ("password", args.password)]
channel = grpc.insecure_channel(args.host + ":" + str(args.port))
stub = gnmi_pb2.gNMIStub(channel)
atexit.register(shutdown_hook)
if args.get:
get(stub, args.get, metadata)
elif args.subscribe:
subscribe(stub, args.subscribe, args.mode, metadata)
else:
subscribe(stub, '/', metadata)
if __name__ == '__main__':
run()