示例#1
0
 def getHardwareAddress(self):
     """
     Provides the client's MAC address.
     
     :return: The client's MAC address.
     """
     length = self.getOption(FIELD_HLEN)[0]
     full_hw = self.getOption(FIELD_CHADDR)
     if length and length < len(full_hw):
         return MAC(full_hw[0:length])
     return MAC(full_hw)
示例#2
0
 def session(self,
             action=None,
             source=None,
             mac=None,
             ipv4=None,
             ipv6=None,
             time=None):
     if cherrypy.request.method != 'POST':
         return "Invalid request method"
     if source not in ('arp', 'nd', 'radius', 'dhcp'):
         return "Invalid source"
     self.authenticate_session_request()
     mac = MAC(mac)
     if ipv4:
         ipv4 = ipaddr.IPv4Address(ipv4)
     if ipv6:
         ipv6 = ipaddr.IPv6Address(ipv6)
     time = datetime.datetime.strptime(time, "%Y-%m-%dT%H:%M:%S")
     if action == 'start':
         sessions.session_started(source, mac, time, ipv4, ipv6)
     elif action == 'end':
         sessions.session_ended(source, mac, time, ipv4, ipv6)
     else:
         return "Invalid action"
     return "Success"
示例#3
0
 def generate_response(self):
     (request, _) = netstring.consume_netstring(self.readbuf)
     (sig, request) = netstring.consume_netstring(request)
     sig = base64.standard_b64decode(sig)
     mysig = hmac.new(ACCESSKEY, request, hashlib.sha256).digest()
     if sig != mysig:
         self.writebuf = b'ERROR Bad signature'
         return
     (action, request) = netstring.consume_netstring(request)
     (mac, request) = netstring.consume_netstring(request)
     (time, request) = netstring.consume_netstring(request)
     if len(request) > 0:
         raise Exception('Invalid request: too long: ' + repr(self.readbuf))
     mac = MAC(mac.decode('ascii'))
     time = datetime.datetime.strptime(time.decode('ascii'),
                                       '%Y-%m-%dT%H:%M:%S')
     now = datetime.datetime.utcnow()
     if time < (now - TIMEWINDOW) or time > (now + TIMEWINDOW):
         self.writebuf = b'ERROR Time out of sync'
         return
     if action not in (b'grant', b'revoke'):
         self.writebuf = b'ERROR Invalid action'
         return
     LOGGER.info('Valid request to {0!r} {1!s}'.format(action, mac))
     if action == b'grant':
         print('grant', str(mac))
     elif action == b'revoke':
         print('revoke', str(mac))
     sys.stdout.flush()
     resp = sys.stdin.readline().strip()
     if resp == 'OK':
         self.writebuf = netstring.encode_netstring(b'OK')
     else:
         self.writebuf = netstring.encode_netstring(b'ERROR ' +
                                                    resp.encode('ascii'))
示例#4
0
    def __init__(self, name=None, mac=None, cable=None):
        if not mac:
            self.mac = MAC()
        else:
            self.mac = mac

        self.name = name
        if cable:
            self.connectCable(cable)
示例#5
0
 def login(self, user=None, mac=None, origurl=None):
     if cherrypy.request.method != 'POST':
         return self.splash(mac, origurl)
     mac = MAC(mac)
     sessions.user_logged_in(user, mac)
     params = {'user': user}
     if origurl:
         params['origurl'] = origurl
     url = '{0}/welcome?{1}'.format(cherrypy.request.base,
                                    urllib.parse.urlencode(params))
     raise cherrypy.HTTPRedirect(url)
示例#6
0
    def splash(self, mac=None, origurl=None):
        macval = MAC(mac)  # Ensures mac is a safe string
        yield """<html>
<head><title>Wifi Login</title></head>
<body>
  <form action="/login" method="POST">
    <input type="hidden" name="mac" value="{mac}"/>
""".format(mac=mac)
        if origurl:
            yield '    <input type="hidden" name="origurl" value={0}/>'.format(
                xml.sax.saxutils.quoteattr(origurl))
        yield """
示例#7
0
def parse_ipneigh_line(line, cons):
    try:
        tokens = line.split()
        state = tokens[-1]
        if state not in VALID_STATES:
            return None
        ip = cons(tokens[0])
        mac = MAC(tokens[tokens.index('lladdr') + 1])
        return (mac, ip)
    except:
        LOGGER.exception("Failed to parse line {0!r}".format(line))
        return None
示例#8
0
def read_OUIs_from_file(filename):
    macs = []
    lines = open(filename).readlines()
    for line in lines:
        line = line.strip()
        if not line:
            continue
        if line[0] == '#':  # skip line that is comment only
            continue

        line_parts = filter(lambda s: s, line.split('\t'))
        line_parts = list(map(lambda s: s.strip(), line_parts))

        if len(line_parts) < 2:
            # we need [mac] and [vendor]
            continue

        line_OUI_part = line_parts[0]
        if line_OUI_part.find('/') > -1:
            # TODO: I don't know how to read this yes.
            continue

        line_vendor_part = line_parts[1]

        if len(line_parts) >= 3:
            line_full_vendor_part = line_parts[2]
            if len(line_parts) >= 4:
                line_comment_part = line_parts[3]
                if len(line_parts) > 4:
                    line = line.replace('\t', '\\t')
                    print(f'Discarding [{" ".join(line_parts[4:])}] '
                          f'from [{line}]')
            else:
                line_comment_part = None
        else:
            line_full_vendor_part = None
            line_comment_part = None

        mac = MAC(line_OUI_part,
                  line_vendor_part,
                  line_full_vendor_part,
                  line_comment_part)

        macs.append(mac)

    return macs
示例#9
0
def all_sessions(con):
    # KLUDGE: This function is entirely too view-oriented, and it's a bad view
    # at that. There should be a more abstract session model, but I needed
    # something quick-n-dirty to see what sessions there were.
    cur = con.execute('''SELECT user_sessions.user, addr_sessions.mac,
                            user_sessions.start, user_sessions.end,
                            addr_sessions.source, addr_sessions.ipv4,
                            addr_sessions.ipv6, addr_sessions.start,
                            addr_sessions.end
                         FROM addr_sessions LEFT OUTER JOIN user_sessions
                            ON addr_sessions.user_session = user_sessions.id
                         ORDER BY addr_sessions.start DESC''')
    # KLUDGE: This should be a generator, but since the generator gets passed
    # back up out of the with_dbconn decorator, the connection is closed before
    # the generator is evaluated.
    return [(row[0], MAC(row[1]), row[2], row[3], row[4], common.bytes_to_ipv4(row[5]),
             common.bytes_to_ipv6(row[6]), row[7], row[8]) for row in cur]
示例#10
0
def end_user_session(con, sessid):
    """Close the user session, revoking access.

    Not for external use, only called from session_ended
    """
    # Pseudocode
    # UPDATE user_sessions SET end = datetime('now') WHERE id = ?
    #  (sessid)
    # SELECT mac FROM user_sessions WHERE id = ?
    #  (sessid)
    # access_control.revoke(mac)
    con.execute('UPDATE user_sessions SET end = datetime(\'now\')'
                ' WHERE id = ?', (sessid,))
    cur = con.execute('SELECT mac FROM user_sessions WHERE id = ?', (sessid,))
    mac = MAC(cur.fetchone()[0])
    try:
        access_control.revoke(mac)
    except:
        logger().exception('Failed to revoke mac {0!s}'.format(mac))
示例#11
0
 def __init__(self, name, ip_address, mac_address, ):
     self.name = name
     self.ip = ip_address
     self.mac = MAC(mac_address)
示例#12
0
###Paths for testing only
#filename = r'G:\Shared drives\datasets\BCI\Competition IV\dataset 2a\Trials\NEW_22ch_A01.mat'
#filename = r'G:\My Drive\Students\vigomez\Code_A1_Application\data_4C\BCI_s02train.mat'
#filename = '..\data_4C\BCI_s01train.mat'

data = sio.loadmat(filename)
Xdata = data['X']
Xdata = np.transpose(Xdata, (2, 1, 0))
labels = data['labels'].reshape(-1, )
fs = 250
print('Loading', filename, 'with sampling frequency of', fs, 'Hz.')

# 2. Artifacts removal stage - Noise Estimation
from mac import MAC
mac_ = MAC(th=args.th)
noise_est = mac_.fit_transform(Xdata, labels)

Noise_sum = np.array([np.sum(noise) for noise in noise_est])
noise_index = np.where(Noise_sum != 0.0)[0]

Xdata = Xdata[noise_index]
Noise = noise_est[noise_index]
labels = labels[noise_index]

#3. Parameter Grid for AMK AF
param_dist = {
    'embedding': randint(5, 10),
    'eta': loguniform(1e-2, 0.5),
    'epsilon': uniform(1e-1, 2),
    'mu': uniform(1e-2, 1),
示例#13
0
 def fit(self,X,y): 
     from mac import MAC
     self.mac = MAC(th=self.th)
     self.mac.fit(X,y)
     return
示例#14
0
y_train = data['labels'].reshape(-1, )
fs = int(data['fs'].reshape(-1, ))
print('Loading', filetrain, 'with sampling frequency of', fs, 'Hz.')
X_train = np.transpose(X_train, (2, 1, 0))  #trials x ch x time

print(X_train.shape, y_train.shape)

# 2. Parameter selection
parameters = pd.read_csv(params)
bp = parameters[parameters.mean_test_score ==
                parameters.mean_test_score.max()].iloc[0]

# AMK parameters

# 3. Pipeline definition and trainnig
steps = [('artifact_removal', MAC(th=0.668963518761388)),
         ('extract', FBCSP(fs, 4, 40, 4, 4, n_components=4)),
         ('select',
          SelectKBest(score_func=mutual_info_classif, k=bp.param_select__k)),
         ('classify', SVC(kernel='linear', C=bp.param_classify__C))]

# ('artifact_removal', ar(th=0.890070294773727))

pipeline = Pipeline(steps=steps)

pipeline.fit(X_train, y_train)

# 4. Prediction
data = sio.loadmat(filetest)
X_test = data['X']
y_test = data['labels'].reshape(-1, )
示例#15
0
args = parser.parse_args()

filename = args.input
savename = args.out

filename = "../../data_4C/BCI_s01train.mat"

data = sio.loadmat(filename)
Xdata = data['X']
labels = data['labels'].reshape(-1, )
fs = int(data['fs'].reshape(-1, ))
print('Loading', filename, 'with sampling frequency of', fs, 'Hz.')
Xdata = np.transpose(Xdata, (2, 1, 0))  #trials x ch x time

steps = [
    ('preproc', MAC()),
    ('extract', FBCSP(fs, 4, 40, 4, 4, n_components=4)),
    #('select', SelectKBest()),
    ('classify', LDA())
]

pipeline = Pipeline(steps=steps)

param_dist = {
    'extract__n_components': [4],
    'extract__fs': [fs],
    'extract__f_low': [4],
    'extract__f_high': [40],
    'extract__bandwidth': [4],
    'extract__step': [4],
    #'select__score_func':[mutual_info_classif],
示例#16
0
 def fit(self, X, y):
     from mac import MAC
     mac_ = MAC(th=self.th)
     self.noise_est = mac_.fit_transform(X, y)
     return
示例#17
0
# weight input interface
in_W = m.Array(y, m.Array(x, TIN))

# Top level module: line buffer input, MAC output
args = ['I0', in_LB, 'I1', in_W, 'WE', m.BitIn,
        'O', out_MAC, 'V', m.Out(m.Bit)] + \
        m.ClockInterface(False, False)
conv = m.DefineCircuit('Convolution', *args)

# Line buffer declaration
lb = Linebuffer(cirb, in_LB, out_LB, imgType, True)
m.wire(conv.I0, lb.I)
m.wire(conv.WE, lb.wen)

# MAC declaration
mac = MAC(x * y)

# connect up linebuffer and weights to MAC input
k = 0
for i in range(y):
    for j in range(x):
        m.wire(lb.out[i][j][0], mac.I0[k])
        m.wire(conv.I1[i][j][0], mac.I1[k])
        k += 1

m.wire(conv.O, mac.O)
m.wire(conv.V, lb.valid)

m.EndCircuit()

module = GetCoreIRModule(cirb, conv)