def l2_check():
  spine_11_new = []
  spine_12_new=[]
  spine_11_l2_output = connect.connect(device['spine-11']['mgmt_ip'],
                                       device['spine-11']['port'],
                                       cmd,
                                       device['spine-11']['username'],
                                       device['spine-11']['password'])
  for x in spine_11_l2_output:
    y = x.split()
    z = ('spine-11', y[0], y[4], y[3])
    spine_11_new.append(z)  
  spine_12_l2_output = connect.connect(device['spine-12']['mgmt_ip'],
                                       device['spine-12']['port'],
                                       cmd,
                                       device['spine-12']['username'],
                                       device['spine-12']['password'])
  for x in spine_12_l2_output:
    y = x.split()
    z = ('spine-12', y[0], y[4], y[3])
    spine_12_new.append(z)
  a = set(spine_11_ls) - set(spine_11_new)
  b = set(spine_12_ls) - set(spine_12_new)
  if not list(a):
    print 'INFO: L2 from Spine-11 is working fine'
  if list(a):
    for m in list(a):
      print 'ERROR: Link failure between %s:%s and %s:%s' % (m[0],m[1],m[2],m[3])
  if not list(b):
    print 'INFO: L2 from Spine-12 is working fine'
  if list(b):
    for m in list(b):
      print 'ERROR: Link failure between %s:%s and %s:%s' % (m[0],m[1],m[2],m[3])
def bgp_check():
  spine_11_new = []
  spine_12_new=[]
  spine_11_l3_output = connect.connect(device['spine-11']['mgmt_ip'],
                                       device['spine-11']['port'],
                                       cmd,
                                       device['spine-11']['username'],
                                       device['spine-11']['password']) 
  for x in spine_11_l3_output:
    y = x.split()
    if y[7] == 'Established':
      z = ('spine-11', y[1], y[0])
      spine_11_new.append(z)
  spine_12_l3_output = connect.connect(device['spine-12']['mgmt_ip'],
                                       device['spine-12']['port'],
                                       cmd,
                                       device['spine-12']['username'],
                                       device['spine-12']['password'])
  for x in spine_12_l3_output:
    y = x.split()
    if y[7] == 'Established':
      z = ('spine-12', y[1], y[0])
      spine_12_new.append(z)  
  a = set(spine_11_bgp) - set(spine_11_new)
  b = set(spine_12_bgp) - set(spine_12_new)
  if not list(a):
    print 'INFO: All BGP peers are connected from Spine-11'
  if list(a):
    for m in list(a):
      print 'ERROR: BGP failure between %s and %s whose AS is %s' % (m[0],m[2],m[1])
  if not list(b):
    print 'INFO: All BGP peers are connected from Spine-12'
  if list(b):
    for m in list(b):
      print 'ERROR: BGP failure between %s and %s whose AS is %s' % (m[0],m[2],m[1])
Beispiel #3
0
    def items(self):
        uncompleted_items_json_data = connect.connect(url="getUncompletedItems", params={'token': self.user.api_token, 'project_id': self.id})
        completed_items_json_data = connect.connect(url="getCompletedItems", params={'token': self.user.api_token, 'project_id': self.id})

        items = item.ItemList(self.user, self)

        for item_data in uncompleted_items_json_data:
            items.append(item.Item(item_data, self.user))

        for item_data in completed_items_json_data:
            items.append(item.Item(item_data, self.user))

        return items
Beispiel #4
0
    def update(self, name=None, color=None, indent=None):
        params = {'token': self.user.api_token, 'project_id': self.id}

        if(name):
            params['name'] = name
            self.name = name
        if(color):
            params['color'] = color
            self.color = color
        if(indent):
            params['indent'] = indent
            self.indent = indent

        connect.connect(method="PUT", url="updateProject", params=params)
Beispiel #5
0
def _run(args, config):
    connection = connect.connect(args, config)
    cursor = connection.cursor()

    cursor.callproc("sync_admin.remove_repo",
                    keywordParameters={
                        "repo_uuid": args.repo})
Beispiel #6
0
def fetch_list_module():
    db = connect(0)
    cur = db.cursor()

    cur.execute("SELECT sn, Card_id FROM Card ORDER by Card.sn ASC")
    rows = cur.fetchall()
    return rows
def history_all_changesets(action):
    conn = connect.connect()
    cur = conn.cursor()
    if action in ['create', 'c']:
        cur.execute("""
            CREATE TABLE history_all_changesets (
              id SERIAL NOT NULL PRIMARY KEY,
              changeset TEXT NOT NULL,
              username TEXT NOT NULL,
              timestamp TEXT NOT NULL,
              created TEXT,
              modified TEXT,
              deleted TEXT
            );
            """)
    elif action in ['truncate', 't']:
        cur.execute("""
            TRUNCATE TABLE history_all_changesets;
            """)
    elif action in ['drop', 'delete', 'd']:
        cur.execute("""
            DROP TABLE history_all_changesets;
            """)
    else:
        raise NotImplementedError(error_message)
    conn.commit()
def history_filters(action):
    conn = connect.connect()
    cur = conn.cursor()
    if action in ['create', 'c']:
        cur.execute("""
            CREATE TABLE history_filters (
              id SERIAL NOT NULL PRIMARY KEY,
              flag INT NOT NULL,
              username TEXT NOT NULL,
              changeset BIGINT NOT NULL,
              timestamp TEXT NOT NULL,
              quantity TEXT NOT NULL
            );
            """)
    elif action in ['truncate', 't']:
        cur.execute("""
            TRUNCATE TABLE history_filters;
            """)
    elif action in ['drop', 'delete', 'd']:
        cur.execute("""
            DROP TABLE history_filters;
            """)
    else:
        raise NotImplementedError(error_message)
    conn.commit()
def _run(args, config):
    connection = connect.connect(args, config)
    cursor = connection.cursor()

    cursor.callproc("sync_admin.unlock_vm_instance",
                    keywordParameters={
                        "vm_instance_uuid": args.vm_instance})
Beispiel #10
0
def add_watched_object(element, reason, author, authorid, email):
    """
    Add object to watched object list.

    Inputs
    ------
    element : str
        Object to track, with type specified as single letter
          prepended to object id (e.g. node 322 is 'n322')
    reason : str
        Reason to track user
    author : str
        User adding tracking entry
    authorid : int
        Userid of user adding entry
    email : str, option
        Email address for notification of events
 
    """
    conn = connect.connect()
    cur = conn.cursor()

    info = (element, reason, author, authorid, email)

    cur.execute("""INSERT INTO watched_objects
                   (element, reason, author, authorid, email)
                   VALUES (%s, %s, %s, %s, %s);""", info)


    conn.commit()
Beispiel #11
0
def fetch_revoked(db, cardid):
	# Get a list of all tests for this card that were revoked:
	con = connect(False, db)
	cur = con.cursor()
	cur.execute("SELECT TestRevoke.test_id FROM TestRevoke, Test WHERE Test.card_id={cardid} AND Test.test_id=TestRevoke.test_id".format(cardid=cardid))
	testids = [item[0] for item in cur.fetchall()]
	return testids
Beispiel #12
0
def complete_items(api_token, ids):
    params={'token': api_token, 'ids': ids}

    if in_history :
        params['in_history'] = in_history

    return connect.connect(url="completeItems", params=params)
Beispiel #13
0
def update_recurring_date(api_token, ids):
    params={'token': api_token, 'ids': ids}

    if js_date :
        params['js_date'] = js_date

    return connect.connect(url="updateRecurringDate", params=params)
Beispiel #14
0
def get_uncompleted_items(api_token, project_id, js_date=None):
    params={'token': api_token, 'project_id': project_id}

    if js_date :
        params['js_date'] = js_date

    return connect.connect(url="getUncompletedItems", params=params)
Beispiel #15
0
def update_item(api_token, item_id,
               content=None, date_string=None, priority=None,
               indent=None, item_order=None, js_date=None):

    params={'token': api_token, 'id': item_id}

    if content :
        params['content'] = content

    if date_string :
        params['date_string'] = date_string

    if priority :
        params['priority'] = priority

    if indent :
        params['indent'] = indent

    if item_order :
        params['item_order'] = item_order

    if js_date :
        params['js_date'] = js_date

    return connect.connect(url="updateItem", params=params)
Beispiel #16
0
def add_whitelisted_user(username, reason, author, authorid):
    """
    Add whitelisted user that is not picked up in tracking.

    Inputs
    ------
    username : str
        Username to track
    reason : str
        Reason to track user
    author : str
        User adding tracking entry
    authorid : int
        Userid of user adding entry
 
    """
    conn = connect.connect()
    cur = conn.cursor()

    info = (username, reason, author, authorid)

    cur.execute("""INSERT INTO whitelisted_users
                   (username, reason, author, authorid)
                   VALUES (%s, %s, %s, %s);""", info)

    conn.commit()
Beispiel #17
0
def add_watched_user(username, reason, author, authorid, email):
    """
    Add user to watched user list for tracking.

    Inputs
    ------
    username : str
        Username to track
    reason : str
        Reason to track user
    author : str
        User adding tracking entry
    authorid : int
        Userid of user adding entry
    email : str, option
        Email address for notification of events
    
    """
    conn = connect.connect()
    cur = conn.cursor()

    info = (username, reason, author, authorid, email)

    cur.execute("""INSERT INTO watched_users
                   (username, reason, author, authorid, email)
                   VALUES (%s, %s, %s, %s, %s);""", info)

    conn.commit()
Beispiel #18
0
def fetch_revokes(db, sn):
	con = connect(False, db)
	cur = con.cursor()
	cur.execute("SELECT TestRevoke.test_id, TestRevoke.comment FROM TestRevoke, Test, Card WHERE Card.sn = {sn} AND Card.card_id = Test.card_id AND Test.test_id = TestRevoke.test_id".format(sn=sn))
	rows = cur.fetchall()		# list of (test_id, comment) items
#	return {test[0]: test[1] for test in rows}		# For >= Python 2.7
	return dict((test[0], test[1]) for test in rows)
Beispiel #19
0
def register(email, full_name, password, timezone):
    if len(password) < 5:
        return "Password should be at least 5 characters long"

    params={'email': email, 'full_name': full_name, 'password': password, 'timezone':timezone}
    json_data, status, response = connect.connect(url="register", params=params, ssl=True)
    return json_data, status, response
Beispiel #20
0
def fetch_tests(db, cardid, attachments=True, inclusive=True):
	# Get a list of tests for this card:
	con = connect(False, db)
	cur = con.cursor()
	
	# Fetch:
	revoked_ids = fetch_revoked(db, cardid)
	tests = OrderedDict()
	for testtype_dict in fetch_types(db, inclusive=inclusive):
		cur.execute("SELECT People.person_name, Test.day, Test.successful, Test.comments, Test_Type.name, Test.test_id FROM Test, Test_Type, People, Card WHERE Test_Type.test_type={0} AND Card.card_id={1} AND People.person_id=Test.person_id AND Test_Type.test_type=Test.test_type_id AND Test.card_id = Card.card_id ORDER BY Test.day ASC".format(testtype_dict["testtype_id"], cardid))
		test_dicts = [{
			"tester": item[0],
			"time": item[1],
			"passed": item[2],
			"comments": item[3],
			"type": item[4],
			"test_id": item[5],
			"revoked": (False, True)[bool(item[5] in revoked_ids)],
		} for item in cur.fetchall()]
		
		result_list = []
		for test_dict in test_dicts:
			cur.execute("SELECT Attachments.attach_id, Attachments.attachmime, Attachments.attachdesc, Attachments.originalname FROM Attachments WHERE Attachments.test_id={0}".format(test_dict["test_id"]))
			test_dict["attachments"] = [{
				"id": item[0],
				"type": item[1],
				"description": item[2],
				"name": item[3],
			} for item in cur.fetchall()]
			result_list.append(test_dict)
		
		tests[(testtype_dict["testtype_id"], testtype_dict["testtype_name"])] = result_list
	return tests
Beispiel #21
0
def history_keys(action):
    conn = connect.connect()
    cur = conn.cursor()
    if action in ['create', 'c']:
        cur.execute("""
            CREATE TABLE history_keys (
              id SERIAL NOT NULL PRIMARY KEY,
              wid INTEGER NOT NULL,
              userid BIGINT NOT NULL,
              key TEXT NOT NULL,
              value TEXT NOT NULL,
              element TEXT NOT NULL,
              username TEXT NOT NULL,
              changeset BIGINT NOT NULL,
              timestamp TEXT NOT NULL,
              action SMALLINT NOT NULL
            );
            """)
    elif action in ['truncate', 't']:
        cur.execute("""
            TRUNCATE TABLE history_keys;
            """)
    elif action in ['drop', 'delete', 'd']:
        cur.execute("""
            DROP TABLE history_keys;
            """)
    else:
        raise NotImplementedError(error_message)
    conn.commit()
Beispiel #22
0
def _run(args, config):
    file_path = os.path.abspath(args.file_path)
    release, build = args.release, args.build

    if args.hash:
        file_size = get_file.get_file_size(file_path)
        file_hash = args.hash
    else:
        file_size, file_hash = get_file.get_file_size_and_hash(file_path)

    if None in [release, build]:
        (extracted_release,
         extracted_build) = _extract_repo_release_and_build(file_path)

        if release is None:
            release = extracted_release
        if build is None:
            build = extracted_build

    connection = connect.connect(args, config)
    cursor = connection.cursor()

    repo_uuid = cursor.callfunc("sync_admin.add_repo",
                                cx_Oracle.STRING,
                                keywordParameters={
                                    "release": release,
                                    "build": build,
                                    "file_path": file_path,
                                    "file_size": file_size,
                                    "file_hash": file_hash})

    output.print_value(repo_uuid, "repo_uuid", args.output)
Beispiel #23
0
def watched_keys(action):
    conn = connect.connect()
    cur = conn.cursor()
    if action in ['create', 'c']:
        cur.execute("""
            CREATE TABLE watched_keys (
              id SERIAL NOT NULL PRIMARY KEY,
              key TEXT NOT NULL,
              value TEXT NOT NULL,
              reason TEXT,
              author TEXT,
              authorid BIGINT,
              email TEXT
            );
            """)
    elif action in ['truncate', 't']:
        cur.execute("""
            TRUNCATE TABLE watched_keys;
            """)
    elif action in ['drop', 'delete', 'd']:
        cur.execute("""
            DROP TABLE watched_keys;
            """)
    else:
        raise NotImplementedError(error_message)
    conn.commit()
def fetch_list_module():
    db = connect(0)
    cur = db.cursor()

    cur.execute("SELECT attach_id FROM Attachments ORDER by Attachments.attach_id ASC")
    rows = cur.fetchall()
    return rows
Beispiel #25
0
def create(userid): #might need to change field names later


    conn = c.connect()
    temp = conn.read('sessions', {'userid': userid})
    #	print temp
    if temp:
        conn.delete('sessions', {'userid': userid})

    conn.clear()

    newid = conn.custom("""
		SELECT MAX(id) as id
		FROM sessions
		""")[0]['ID']

    if newid:
        newid += 1
    else:
        newid = 1

    #change format of the expiration if needed here #%b
    #	if now.day + 2  > 30 :
    #		day = -1
    #	expdate = str((day + 2)) + now.strftime("-%b-") + str(now.year)# + " " + str(now.second) + ":" + str(now.minute) + ":" + str(now.hour)
    #	print expdate
    #expdate = "%d-%s-%d %d:%d" % (now.day + 2, now.strftime("%b"), now.year, now.minute, now.hour)
    #	conn.create('sessions', {'userid' : userid, 'id' : newid, 'expired' : expdate})
    conn.create('sessions', {'userid': userid, 'id': newid})

    return newid
Beispiel #26
0
def main():
	# Arguments:
	form = cgi.FieldStorage()
	sn = form.getvalue("serial_number")
	db = settings.get_db()

	if sn:
		try:
			con = connect(True, db)
			cur = con.cursor()
			cur.execute("INSERT INTO Card SET sn = '{0}'; ".format(sn)) 
			con.commit()	
			con.close()
	
		except Exception as ex:
			base.begin()
			base.header(title='{0}: add module'.format(db))
			base.top(db)
			print ex
			print '<center><h3 style="color:red"><i>Serial number "{0}" already exists! It was not added.</i></h3></center>'.format(sn)

		else:
			cardid = module.fetch_cardid_from_sn(db,sn)
			base.begin()
			base.header_redirect("module.py?db={0}&card_id={1}".format(db,cardid))
			base.top(db)
	else:
		base.begin()
		base.header_redirect("home.py?db={0}".format(db),1)
		base.top(db) 
		print '<center><h3 style="color:red"><i>Tried to input null serial number. Do not do that.</i></h3></center>'.format(sn)
	
	base.bottom()
def add_test(person_id, test_type, serial_num, success, comments):
    if success:
        success = 1
    else:
        success = 0

    db = connect(1)
    cur = db.cursor()

    if serial_num:
        cur.execute("SELECT card_id FROM Card WHERE sn = %(n)d" %{"n":serial_num})
        row = cur.fetchone()
        card_id = row[0]
        
        sql="INSERT INTO Test (person_id, test_type_id, card_id, successful, comments, day) VALUES (%s,%s,%s,%s,%s,NOW())"
        # This is safer because Python takes care of escaping any illegal/invalid text
        items=(person_id,test_type,card_id,success,comments)
        cur.execute(sql,items)
        test_id = cur.lastrowid

        db.commit()

        return test_id        
    else:
        print '<div class ="row">'
 	print			'<div class = "col-md-3">'
 	print                       '<h3> Attempt Failed. Please Specify Serial Number </h3>'
 	print                   '</div>'
 	print  '</div>'

 	add_test_template(serial_num)
Beispiel #28
0
def login(fields, cookie):
    if fields.has_key('user') and fields.has_key('password'):
        user = fields['user'].value #.value
        password = fields['password'].value #.value

        db = connect.connect()
        temp = db.read('users', {'userid': user})
        #print temp # testing
        # user does exist and password matches
        if temp and temp[0]['PASSWORD'] == password:
            # create session cookie
            sid = sessions.create(user)
            newcookie = 'id=' + str(sid)
            # redirect to catalogue menu page
            t = loader('loggedin')
            c = Context({}) #TODO
            print http_response(t.render(c), newcookie)

        # no match
        else:
            t = loader('login')
            c = Context({'errors': 'Incorrect username or password. Also, I slept with your sister.'})
            print http_response(t.render(c))
        # go back to login page with error message
    else:
        t = loader('login')
        c = Context({})
        print http_response(t.render(c))
def _run(args, config):
    connection = connect.connect(args, config)
    cursor = connection.cursor()

    cursor.callproc("sync_admin.reset_device_secret",
                    keywordParameters={
                        "device_uuid": args.device})
Beispiel #30
0
def add_watched_key(key, value, reason, author, authorid, email):
    """
    Add key/value combination to key/value tracking list.

    Inputs
    ------
    key : str
        Key to track; can be wildcard
    value : str
        Key value to track; can be wildcard
    reason : str
        Reason to track user
    author : str
        User adding tracking entry
    authorid : int
        Userid of user adding entry
    email : str, option
        Email address for notification of events
 
    """
    conn = connect.connect()
    cur = conn.cursor()

    info = (key, value, reason, author, authorid, email)

    cur.execute("""INSERT INTO watched_keys
                   (key, value, reason, author, authorid, email)
                   VALUES (%s, %s, %s, %s, %s, %s);""", info)

    conn.commit()