def certificates(): session = login() baseurl = "https://sandboxsdwan.cisco.com:8443" #baseurl = "https://10.10.20.90:8443" headers = {"Accept": "application/json"} # Get all certificates certificate_endpoint = "/dataservice/certificate/vsmart/list" url = f"{baseurl}{certificate_endpoint}" response_certificate = session.get(url, headers=headers, verify=False).json() certificates = response_certificate['data'] for certificate in certificates: print( f"certificate: {certificate['deviceType']} with serial nr {certificate['serialNumber']} expires at {certificate['expirationDate']} " ) # Get root certificate root_endpoint = "/dataservice/certificate/rootcertificate" url = f"{baseurl}{root_endpoint}" response_certificate = session.get(url, headers=headers, verify=False).json() print(response_certificate['rootcertificate'])
def erp_login(request, redirect_url): #check session, if is login, redirect to redirect_url if request.session['erp_user'] is not None: return HttpResponseRedirect(redirect_url) #else do login if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['login'] password = form.cleaned_data['password'] # try login result = auth.login(request, username, password) if result: response = HttpResponseRedirect(redirect_url) if settings.ERP_DOMAIN == 'localhost': response.set_cookie('sid', result[0]) response.set_cookie('instance0|session_id', '%%22%s%%22' % result[1]) else: response.set_cookie('sid', result[0], domain=settings.ERP_DOMAIN) response.set_cookie('instance0|session_id', '%%22%s%%22' % result[1], domain=settings.ERP_DOMAIN) return response else: form.erperror = u'\u9519\u8bef\u7684\u7528\u6237\u540d\u6216\u5bc6\u7801' return render_to_response("updisauth/login.html", {'form': form}, context_instance=RequestContext(request)) else: form = LoginForm() return render_to_response("updisauth/login.html", {'form': form}, context_instance=RequestContext(request))
def build_template(): session = login() baseurl = "https://10.10.20.90:8443" headers = { "Accept": "application/json", "Content-Type": "application/json" } # Get all feature templates feature_templates = get_feature_templates() payload = { "templateName": "Basic_template", "templateDescription": "Collection of default templates", "deviceType": "vsmart", "configType": "template", "factoryDefault": False, "policyId": "", "featureTemplateUidRange": [], "generalTemplates": feature_templates } # template_endpoint = "/dataservice/template/device/feature" url = f"{baseurl}{template_endpoint}" response_template = session.get(url, headers=headers, data=json.dumps(payload), verify=False).json() pprint(response_template)
def get_feature_templates(): session = login() # baseurl = "https://10.50.221.182:8443" baseurl = "https://sandboxsdwan.cisco.com:8443" template_endpoint = "/dataservice/template/feature" url = f"{baseurl}{template_endpoint}" response_template = session.get(url, verify=False).json() #pprint(response_template) templates = response_template['data'] feature_templates = [] for template in templates: print( f"Template with id {template['templateId']} (Factory Default: {template['factoryDefault']})" ) print( f"Template with id {template['templateId']} (Template Type: {template['templateType']})" ) feature_templates.append({ "templateId": template['templateId'], "templateType": template['templateType'], }) for device in template['deviceType']: print(f" Associated device => {device}") return feature_templates
def controller_status(): session = login() baseurl = "https://sandboxsdwan.cisco.com:8443" #baseurl = "https://10.10.20.90:8443" headers = { "Accept": "application/json", "Content-Type": "application/json" } # Get certificate summary control_endpoint = "/dataservice/device/control/count" url = f"{baseurl}{control_endpoint}" response_control = session.get(url, headers=headers, verify=False).json() statusList = response_control['data'][0]['statusList'] for status in statusList: print(f"{status['count']} {status['message']}") if not (status['count']) == 0: print(" Checking for more details: ") detail_endpoint = status['detailsURL'] url = f"{baseurl}{detail_endpoint}" response_detail = session.get(url, headers=headers, verify=False).json() #pprint(response_detail) details = response_detail['data'] #pprint(details) for detail in details: print(f" {detail['device-model']} device with UUID {detail['uuid']} and IP {detail['system-ip']} ")
def create_user(): session = login() baseurl = "https://10.50.221.182:8443" payload = { "group": ["netadmin"], "description": "User Wim", "userName": "******", "password": "******", } headers = { "Accept": "application/json", "Content-Type": "application/json" } user_endpoint = "/dataservice/admin/user" url = f"{baseurl}{user_endpoint}" response_user = session.post(url, headers=headers, data=json.dumps(payload), verify=False) print(response_user.text)
def get_csr1000v(): session = login() baseurl = "https://10.50.221.182:8443" controller_endpoint = "/dataservice/system/device/vedges?model=vedge-CSR-1000v" url = f"{baseurl}{controller_endpoint}" response_controller = session.get(url, verify=False).json() devices = response_controller['data'] for device in devices: print(f"CSR1000v device => {device['deviceModel']} with serialnumber {device['serialNumber']}")
def get_vedges(): session = login() baseurl = "https://10.50.221.182:8443" vedge_endpoint = "/dataservice/system/device/vedges" url = f"{baseurl}{vedge_endpoint}" response_controller = session.get(url, verify=False).json() vedges = response_controller['data'] for vedge in vedges: print(f"vEdge device => {vedge['deviceModel']} with serialnumber {vedge['serialNumber']}")
def auth(): if (request.form['action'] == "login"): out = authenticate.login(request.form['user'], request.form['password']) try: if (out[1] == 1): session['user'] = request.form['user'] return redirect(url_for('index')) except: ## return redirect(url_for('home')) ## return redirect(url_for('home', out='foo')) return render_template('home.html', out='Rocky') elif (request.form['action'] == "register"): return authenticate.register(request.form['user'], request.form['password'])
def get_templates(): session = login() # baseurl = "https://10.50.221.182:8443" baseurl = "https://sandboxsdwan.cisco.com:8443" template_endpoint = "/dataservice/template/device" url = f"{baseurl}{template_endpoint}" response_template = session.get(url, verify=False).json() #pprint(response_template) templates = response_template['data'] for template in templates: print(f"Template => {template['deviceType']} with id {template['templateId']}")
def get_devicecontrollers(): session = login() #baseurl = "https://10.50.221.182:8443" baseurl = "https://sandboxsdwan.cisco.com:8443" controller_endpoint = "/dataservice/system/device/controllers" url = f"{baseurl}{controller_endpoint}" print(url) response_controller = session.get(url, verify=False) devices = response_controller.json()['data'] for device in devices: print( f"Device controller => {device['deviceType']} with IP address {device['deviceIP']}" )
def stats(): session = login() baseurl = "https://sandboxsdwan.cisco.com:8443" #baseurl = "https://10.10.20.90:8443" headers = { "Accept": "application/json", "Content-Type": "application/json" } # Get alarm count alarms_endpoint = "/dataservice/alarms/count" url = f"{baseurl}{alarms_endpoint}" response_alarms = session.get(url, headers=headers, verify=False).json() print(f"Cleared alarms: {response_alarms['data'][0]['cleared_count']}") print(f"Count: {response_alarms['data'][0]['count']}")
def get_device_control_connections(): session = login() baseurl = "https://sandboxsdwan.cisco.com:8443" #baseurl = "https://10.50.221.182:8443" params = {"deviceId": "4.4.4.60"} control_endpoint = "/dataservice/device/control/connections" url = f"{baseurl}{control_endpoint}" response_controlconn = session.get(url, params=params, verify=False) connections = response_controlconn.json()['data'] for conn in connections: print( f"Hostname: {conn['vdevice-host-name']} (type: {conn['peer-type']}) with public IP {conn['public-ip']}" )
def change_password(): session = login() #baseurl = "https://sandboxsdwan.cisco.com:8443" baseurl = "https://10.10.20.90:8443" payload = { "userName": "******", "password": "******", } headers = { "Accept": "application/json", "Content-Type": "application/json" } pwchange_endpoint = "/dataservice/admin/user/password/wim" url = f"{baseurl}{pwchange_endpoint}" response_pw = session.put(url, headers=headers, data=json.dumps(payload), verify=False) print(response_pw.text)
def certificate_summary(): session = login() baseurl = "https://sandboxsdwan.cisco.com:8443" #baseurl = "https://10.10.20.90:8443" headers = { "Accept": "application/json", "Content-Type": "application/json" } # Get certificate summary certificate_endpoint = "/dataservice/certificate/stats/summary" url = f"{baseurl}{certificate_endpoint}" response_certificate = session.get(url, headers=headers, verify=False).json() print( f"Invalid certificates: {response_certificate['data'][0]['invalid']}") print( f"Certificates Warnings: {response_certificate['data'][0]['warning']}")
def get_auditlog(): session = login() baseurl = "https://sandboxsdwan.cisco.com:8443" #baseurl = "https://10.10.20.90:8443" headers = { "Accept": "application/json", "Content-Type": "application/json" } # Get alarm count auditlog_endpoint = "/dataservice/auditlog" url = f"{baseurl}{auditlog_endpoint}" response_auditlog = session.get(url, headers=headers, verify=False).json() auditlogs = response_auditlog['data'] for auditlog in auditlogs: print( f"Device: {auditlog['logdeviceid']} -- User: {auditlog['loguser']} -- Message: {auditlog['logmessage']} " )
import json, requests, authenticate, runtime def findKey(d, key): if key in d: yield d[key] for k in d: if isinstance(d[k], list) and k == 'children': for i in d[k]: for j in findKey(i, key): yield j # This is where we connect to ArchivesSpace. See authenticate.py baseURL, headers = authenticate.login() repoID = input('Enter repository ID:') resourceID = input('Enter resource ID: ') endpoint = '/repositories/' + repoID + '/resources/' + resourceID + '/tree' try: output = requests.get(baseURL + endpoint, headers=headers).json() except requests.exceptions.RequestException as e: print( "Invalid URL. Try running the script again with different repository and/or resource numbers." ) exit() archivalObjects = [] for value in findKey(output, 'record_uri'):
def main(): # Login to SaltyBet user = input("Email: ") pwd = getpass.getpass() session, request = authenticate.login(user, pwd) site = saltysite.scrape(session, request) db = saltydb.Database('saltybet.sqlite3.bin') print_welcome_message() print_user_stats(site.get_USER_leaderboard_rank(), site.get_USER_bet_streak(), site.get_USER_balance()) prev_status, status = "None", "None" prev_balance = site.get_USER_balance() placed_bet = False # This dictionary will build a result.json file for historical checking Salty_Bet = dict() while(True): time.sleep(7) prev_status = status site.update() status = site.get_betting_status() if(prev_status != status): user_balance = site.get_USER_balance() player1name = site.get_player1_name() player2name = site.get_player2_name() player1stats = db.retrieve_fighter(player1name) player2stats = db.retrieve_fighter(player2name) (Pa, Pb) = ExpectedProbabilities(player1stats.get('elo'), player2stats.get('elo')) # Status can be open, locked, 1, 2 (the numbers denote player1 or player2 victory) if(prev_status != 'open' and status == 'open'): if(placed_bet): print_last_match_results(prev_balance, user_balance, placed_bet) changed = user_balance - prev_balance Salty_Bet.update({'Delta':changed}) with open('result.json', 'a+') as fp: json.dump(Salty_Bet, fp) fp.write('\n') # if changed > 100,000 -> play # if changed > 500,000 -> play # if changed > 1,000,000 -> play # if changed > -100,000 -> play # if changed > -500,000 -> play # if changed > -1,000,000 -> play print_user_stats(site.get_USER_leaderboard_rank(), site.get_USER_bet_streak(), site.get_USER_balance()) print_match_details(player1stats, player2stats, Pa, Pb) placed_bet = False isP1favored = Pa > Pb # simulate matches so that we select underdogs at same percentage of their win chance sim_game = random.randrange(0, 9999, 1) #hardcode 10000 matches; step of 1 didP1win = sim_game < (Pa * 10000) if (didP1win == True and isP1favored == True): fighter = player.P1 current_bet = player1stats['fighter'] print(f"SIMULATING :: Taking the favorite with fighter {player1stats['fighter']}") elif (didP1win == True and isP1favored == False): fighter = player.P1 current_bet = player1stats['fighter'] print(f"SIMULATING :: Taking the underdog with fighter {player1stats['fighter']}") elif (didP1win == False and isP1favored == True): fighter = player.P2 current_bet = player2stats['fighter'] print(f"SIMULATING :: Taking the underdog with fighter {player2stats['fighter']}") else: #(didP1win == False & isP1favored == False): fighter = player.P2 current_bet = player2stats['fighter'] print(f"SIMULATING :: Taking the favorite with fighter {player2stats['fighter']}") # determine_wager - would be nice to put some real logic here some day! game_mode = site.get_match_type() if game_mode == "bracket": if (user_balance > 10000): wager = int(user_balance * 0.1) else: wager = user_balance elif game_mode == "exhibition": wager = 1 else: if (user_balance < 3000): wager = user_balance elif (user_balance < 10000): wager = int(user_balance * .5) elif (user_balance < 1000000): wager = int(user_balance * 0.05) else: wager = int(user_balance * 0.02) try: placebet(session, fighter, wager) except: print("Error placing bet.") prev_balance = user_balance placed_bet = True Salty_Bet.clear() Salty_Bet.update({'Balance':user_balance, 'P1':player1name, 'P2':player2name, 'P1-win':Pa, 'P2-win':Pb, 'Wager':wager, 'GameMode':game_mode}) elif (prev_status == 'open' and status == 'locked'): if (int(site.get_player1_wagers()) > int(site.get_player2_wagers())): odds = int(site.get_player1_wagers()) / int(site.get_player2_wagers()) if (fighter == player.P1): odds = 1 / odds else: odds = int(site.get_player2_wagers()) / int(site.get_player1_wagers()) if (fighter == player.P2): odds = 1 / odds print_bet_details(current_bet, wager, odds) print_site_message(site.get_remaining()) Salty_Bet.update({'Odds':odds}) elif (prev_status != '1' and status == '1'): print_winner(site.get_player1_name()) (Wr, Lr) = DetermineNewRankings(player1stats.get('elo'), Pb, player2stats.get('elo'), Pa) db.insert_ranking(site.get_player1_name(), Wr, site.get_player2_name(), Lr) Salty_Bet.update({'Winner':'P1'}) elif (prev_status != '2' and status == '2'): print_winner(site.get_player2_name()) (Wr, Lr) = DetermineNewRankings(player2stats.get('elo'), Pb, player1stats.get('elo'), Pa) db.insert_ranking(site.get_player2_name(), Wr, site.get_player1_name(), Lr) Salty_Bet.update({'Winner':'P2'})
def main(): """ The main run loop for SaltBot """ # Login to SaltyBet session, request = authenticate.login() # Connect to Database conn, cur = database.connect() # Setup website interface site = website.interface(session, request) # Create global variables balance_start, balance_end = site.get_balance(), site.get_balance() status, prev_status = "None", "None" duration = 0 placed_bet = False state = match_state.invalid # Create a match dictionary match = { 'player1': '', 'player2': '', 'duration': '', 'p1bet': '', 'p2bet': '', 'myplayer': '', 'mybet': '', 'winner': '' } while (True): try: # Add a delay to avoid overloading the server time.sleep(10) duration += 10 # Update status prev_status = status site.update() status = site.get_betting_status() # Note: The status can be open, locked, 1, 2. The last two # statuses denote player1, player2 victory if (prev_status != 'open' and status == 'open'): # End of previous match. # The placed_bet check is these to ensure that the match had begun and we fully populated the match dict before storing to PostgreSQL if placed_bet: balance_end = site.get_balance() if (balance_end > balance_start): print('Our bet wins') match['winner'] = match['myplayer'] if match['player1'] == match['myplayer']: state = match_state.p1_win else: state = match_state.p2_win elif (balance_end < balance_start): print('Our bet loses') if match['myplayer'] == match['player1']: match['winner'] = match['player2'] state = match_state.p2_win else: match['winner'] = match['player1'] state = match_state.p1_win else: print('Start $: ' + str(balance_start) + ' End $: ' + str(balance_end)) print('Money remained the same?') match['winner'] = '???' state = match_state.tie match['duration'] = duration # Save the match database.save_match(match, conn, cur) # Add players to table if not already there for p in [match['player1'], match['player2']]: if not database.has_player(p, cur): database.add_player(p, conn, cur) # Update player tables if match_state.p1_win == state: database.record_win(match['player1'], match['duration'], conn, cur) database.record_loss(match['player2'], match['duration'], conn, cur) elif match_state.p2_win == state: database.record_win(match['player2'], match['duration'], conn, cur) database.record_loss(match['player1'], match['duration'], conn, cur) elif match_state.tie == state: database.record_tie(match['player1'], match['player2'], conn, cur) # Start of new match print('\nBetting is now open!') print('Balance: ' + str(balance_end)) match['player1'] = site.get_player1_name() match['player2'] = site.get_player2_name() wager = determine_wager(balance_end) predicted_winner = determine_player(match['player1'], match['player2'], cur) # Place the bet, refresh the status to determine success bet(session, predicted_winner, wager) match['myplayer'] = match[predicted_winner.value] match['mybet'] = wager placed_bet = True # Player win percentage if database.has_player(match['player1'], cur): print("P1: " + str( database.get_player_percent_wins( match['player1'], cur))) if database.has_player(match['player2'], cur): print("P2: " + str( database.get_player_percent_wins( match['player2'], cur))) print("P1: " + match['player1'] + " P2: " + match['player2']) print("Bet " + str(wager) + " on " + match['myplayer']) elif (prev_status == 'open' and status == 'locked'): print('The match begins!') balance_start = site.get_balance() duration = 0 match['p1bet'] = site.get_player1_wagers() match['p2bet'] = site.get_player2_wagers() except Exception as err: cur.close() conn.close() sys.stderr.write('ERROR: {0} on line {1}\n'.format( str(err), sys.exc_info()[-1].tb_lineno))
if(PWD == ""): PWD = "." if(len(sys.argv) == 1 and AUTHENTICATED == True): l = open(LOGFILE, "r") j = json.load(l) user = j["USER"] print('You are already logged in as ' + user) utils.recieve_files(USER, PWD, SERVER,TOKEN) l.close() elif(len(sys.argv) == 1 and AUTHENTICATED == False): input_user = input("Enter Username : "******"Enter Password : "******"Enter server : ") ans, TOKEN = authenticate.login(input_user, input_pwd, SERVER, True) if(ans): print("AUTHENTICATED. Hello", input_user) l = open(LOGFILE, "w") j["SERVER"] = SERVER j["USER"] = input_user j["PWD"] = PWD j["AUTHENTICATED"] = True j["TOKEN"] = TOKEN json.dump(j, l) l.close() else: print("ACCESS DENIED") l = open(LOGFILE, "w") j["USER"] = "" json.dump(j, l)
def setup(): session, request = login() return interface(session, request)
def test_login(): session, request = login() assert (session != None) assert (request != None)
def login(): email = request.args["email"] password = request.args["password"] return authenticate.login(username, password)
def login(self): RET = hf.start() + hf.headers() + hf.style() + sa.login() return RET