How to use running_os_release method in autotest

Best Python code snippet using autotest_python

hello.py

Source:hello.py Github

copy

Full Screen

1#! /usr/bin/env python2# buil a simple movie DB using3# https://www.google.com/search?q=list+of+movies+w%2F+expired+copyrights&oq=list+of+movies+w%2F+expired+copyrights&aqs=chrome..69i57.10974j0j7&sourceid=chrome&ie=UTF-84# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -5from flask import Flask, render_template, request, jsonify, make_response6app = Flask(__name__)7import json # JSON tools8# debug9from pprint import pprint # giza a look10import inspect # inspect.getmembers(object[, predicate])11# dir file12# this causes __init_.py to execute13from moviepicker import MMediaLib,MMedia,REVERSE,FORWARD,media_cloud,UserPrefs,load_dict_data_from_DB,commit_dict_to_DB14from pathlib import Path15import random16import re # regex17import socket18import copy19import sys20from collections import Counter21import subprocess22from time import sleep23import vlc24from moviepicker import vlc_http, kill_running_vlc # needs an instance of vlc running25vlc_http_channel = None26movie_process = None27media_lib = None28# Look for available DBs & load info29# Note30# default_library_name = 'medialib2.pickle'31# default_parent_folder = '__media_data2'32# default_media_parent = 'movies'33#34# disk_path/movies/__media_data2/medialib2.pickle35# | | | |36# | | | DB file37# | | DB parent folder38# | media folder39# rebaseable parent path40import platform41running_os = platform.system()42# AIX: 'aix', Linux:'Linux', Windows: 'win32', Windows/Cygwin: 'cygwin', macOS: 'Darwin'43running_os_release = platform.release()44hostname = socket.gethostname()45print("Your Computer Name is:" + hostname)46IPAddr = socket.gethostbyname(hostname)47print("Your Computer IP Address is:" + IPAddr)48print(f"OS: {running_os} - {running_os_release}")49#media_lib = MMediaLib(media_cloud.main)50# if running_os == 'Darwin' or running_os == 'Linux':51# 52# print("Building media_lib from the following sources:")53# pprint(media_cloud.known_paths)54# if len(media_cloud.known_paths) > 1:55# 56# for m in media_cloud.known_paths:57# mmdbs = [MMediaLib(db_path) for db_path in media_cloud.known_paths]58# 59# media_lib = mmdbs.pop()60# 61# while len(mmdbs) > 0:62# media_lib.addLibAndRebuild(mmdbs.pop())63# 64# elif media_cloud.main:65# media_lib = MMediaLib(media_cloud.main)66# 67# if not media_lib:68# print("EXITIING - NO media libraries were found\nChecked:")69# print(f"IP: {IPAddr} OS:{running_os} ver:{running_os_release}")70# for p in media_cloud.known_paths:71# print(p)72# 73# sys.exit(0)74media_lib = MMediaLib(Path('/Volumes/Osx4T/tor/__media_data2/medialib2.pickle'))75LOCAL_IMAGE_CACHE = Path('./static/covers')76LOCAL_IMAGE_CACHE.mkdir(parents=True, exist_ok=True)77# TODO this may still be on an external disk - avoid using local SDcard on rpi /78media_lib.cache_images_locally(LOCAL_IMAGE_CACHE)79print(f"LOADED: {len(media_lib)}")80# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -81# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -82# users / prefs proto - move into module83# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -84user_device_DB = {}85load_dict_data_from_DB(user_device_DB)86import uuid87print("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - JSON DB - S")88new_uuid = str(uuid.uuid4())89new_uuid = list(user_device_DB.keys())[3] # dont add any more users!90current_user = None91print("users:")92for k in user_device_DB.keys():93 user = user_device_DB[k]94 print(f"u: {user.uuid()} n:{user.name} t:{type(user)}")95print(f"New UUID: {new_uuid}")96if new_uuid not in user_device_DB:97 u = UserPrefs(new_uuid, f"U{len(user_device_DB.keys())}")98 user_device_DB[u.uuid()] = u99 pprint(user_device_DB)100 commit_dict_to_DB(user_device_DB)101else:102 print(f"FOUND USER: {new_uuid}")103 pprint(user_device_DB[new_uuid].info)104 # user_device_DB[new_uuid].info['current_user'] = True105 # commit_dict_to_DB(user_device_DB)106for usr_id,usr in user_device_DB.items():107 #print(f"\n===== u: {usr_id} n:{usr.name} t:{type(usr)} current:{usr.info['current_user']}")108 #pprint(usr.info)109 if usr.info['current_user']: current_user = usr110#commit_dict_to_DB(user_device_DB)111users_nav_bar = []112def update_users_for_navbar():113 global users_nav_bar114 users_nav_bar.clear()115 for key_uuid,user_prefs in user_device_DB.items():116 users_nav_bar.append({'usr':user_prefs.name, 'user_uuid':key_uuid})117update_users_for_navbar()118print("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - JSON DB - E")119# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -120#<a href="{{url_for('/', user_id=u['user_uuid'])}}">{{ u['usr'] }}</a>121show_single_movie = None122#@app.route('/<user_id>', methods=["GET", "POST"])123@app.route('/', methods=["GET", "POST"])124def movie_gallery_home():125 global show_single_movie126 global current_user127 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #128 # reset vlc process #129 # #130 # catch this in JS land - if multiple devices connect #131 # TODO - think through multiuser use cases #132 # back to selections menu - kills movie window #133 global movie_process #134 global vlc_http_channel #135 #136 # TODO - is this used anymore? or is it just kill_running_vlc() #137 # REMOVE? #138 if movie_process: #139 # record movie and place in movie - if reselected restart where left off!! MVTODO #140 movie_process.kill() #141 movie_process = None #142 #143 kill_running_vlc() #144 vlc_http_channel = None #145 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #146 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#147 # processing incoming msgs #148 # https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request149 print(f"\nmovie_gallery_home: - - - - - - - - debug - - - - - - - - - - - - - - - - S\n") #150 if request.method == 'POST': #151 if request.is_json:152 print("movie_gallery_home: request.method == 'POST_JSON'")153 settings = request.get_json() # parse JSON into DICT154 pprint(settings)155 if settings != None and 'show_mov_id' in settings:156 print(f"> > SHOW SINGLE MOVIE REQUEST - < {settings['show_mov_id']} >")157 show_single_movie = settings['show_mov_id']158 return json.dumps({}), 201 # created159 if settings != None and 'prefs_info' in settings:160 try:161 user_device_DB[settings['prefs_info']['uuid']].update_prefs(settings['prefs_info'])162 commit_dict_to_DB(user_device_DB)163 # return all good164 return json.dumps({}), 201 # created165 except (UserUuidMismatch, KeyError):166 # return - couldnt find user_info!??167 return json.dumps({}), 404168 if settings != None and 'new_id' in settings: # user id169 try:170 last_user = current_user171 current_user = user_device_DB[settings['new_id']]172 current_user.info['current_user'] = True173 if current_user != last_user: last_user.info['current_user'] = False174 commit_dict_to_DB(user_device_DB)175 return json.dumps({}), 201 # user changed176 except KeyError:177 # return - couldnt find user_info!??178 return json.dumps({}), 404179 if settings != None and 'mov_id_prefs' in settings:180 print("'mov_prefs' in settings - - - S")181 button = re.sub('mov_prefs_','', settings['button']) # which movie pref button?182 mov_id = settings['mov_id_prefs']183 rating = settings['rating']184 print(f"mov_prefs clicked: {button}")185 if button == 'sl':186 if mov_id not in current_user.info['short_list']: current_user.info['short_list'].append(mov_id)187 commit_dict_to_DB(user_device_DB)188 return json.dumps({}), 201189 elif button == 'ni':190 if mov_id not in current_user.info['ni_list']: current_user.info['ni_list'].append(mov_id)191 commit_dict_to_DB(user_device_DB)192 return json.dumps({}), 201193 elif button == 'rate':194 if (rating != -1):195 current_user.info['ratings'][mov_id] = rating196 commit_dict_to_DB(user_device_DB)197 return json.dumps({}), 201198 return json.dumps({}), 404199 elif button == 'seen':200 if mov_id not in current_user.info['seen_list']: current_user.info['seen_list'].append(mov_id)201 commit_dict_to_DB(user_device_DB)202 return json.dumps({}), 201203 print("'mov_prefs' in settings - - - E")204 else:205 print("movie_gallery_home: request.method == 'POST' - NOT json ")206 print("\nrequest.args - - - - <")207 pprint(request.args)208 for key in request.args.keys(): #209 print(f"{key} - {request.args[key]}") #210 print("\nrequest.form - - - - <")211 pprint(request.form)212 else:213 if request.is_json:214 print("movie_gallery_home: request.method == 'POST_JSON'")215 settings = request.get_json() # parse JSON into DICT216 pprint(settings)217 if settings != None and 'show_mov_id' in settings:218 print(f"> > SHOW SINGLE MOVIE REQUEST - < {settings['show_mov_id']} >")219 else:220 print(f"movie_gallery_home: request.method == {request.method}")221 print(f"PROCESSING SINGLE MOVIE REQUEST - {show_single_movie} - <")222 print(f"\nmovie_gallery_home: - - - - - - - - debug - - - - - - - - - - - - - - - - E\n")223 # #224 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#225 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -226 # generate gallery sorted by request227 #228 test_version = '0.0.0'229 print(f"Vs: {test_version}")230 if show_single_movie:231 page='movie_gallery_single'232 movies = [media_lib.media_with_id(show_single_movie)]233 show_single_movie = None234 pprint(movies[0])235 else:236 page='movie_gallery_home'237 movies = media_lib.getMovieList(current_user)238 global users_nav_bar239 genres = media_lib.genres240 info = current_user.info241 pprint(info)242 return render_template('gallery_grid.html', movies=movies, prefs_info=info, users_nav_bar=users_nav_bar, genres=genres, page=page)243#<a href="{{url_for('/', user_id=u['user_uuid'])}}">{{ u['usr'] }}</a> < - - - - - - #244#@app.route('/<user_id>', methods=["GET", "POST"]) #245@app.route('/slider_tests', methods=["GET", "POST"]) #246def slider_tests(): #247 global current_user # TODO - should be a user session / login - passed in /248 print('> > /slider_tests')249 print(f"media_lib size: {len(media_lib)}")250 all_slider_movies = media_lib.getSliderMovieList(current_user)251 genres = media_lib.genres252 info = current_user.info253 pprint(info)254 global users_nav_bar255 return render_template('slider_tests.html', movies=all_slider_movies, prefs_info=info, users_nav_bar=users_nav_bar, genres=genres, page='slider_tests')256@app.route('/play_movie/<movie_id>', methods=["GET", "POST"])257def play_movie(movie_id):258 # copy so as not to change objects in media lib to strings259 movie = copy.copy(media_lib.media_with_id(movie_id))260 movie['cast'] = [ str(mv) for mv in movie['cast'] ]261 movie['file_path'] = str(movie['file_path'])262 movies = [movie]263 global vlc_http_channel264 global movie_process265 # fire up VLC and a connection to it266 if movie_process == None:267 print(f"\n\n\n-=-=-=-=- STARTING MOVIE -=-=-=-=-\n")268 print(f"running_os:{running_os}")269 if running_os == 'Linux':270 #cmd = ['vlc', '-f', movie['file_path'], '--extraintf', 'http']271 cmd = ['vlc', movie['file_path'], '--extraintf', 'http']272 movie_process = subprocess.Popen(cmd)273 elif running_os == 'Darwin':274 movie_process = subprocess.Popen(f"exec /Applications/VLC.app/Contents/MacOS/VLC -f '{movie['file_path']}' --extraintf http", shell=True)275 # how to get a callback on processed termination276 # https://wiki.videolan.org/Documentation:Advanced_Use_of_VLC/277 # how to open in full screen mode? -f option278 sleep(0.5)279 print(f"\n-=-=-=-=- STARTING MOVIE -=-=-=-=-\n\n\n")280 if vlc_http_channel == None:281 print(f"\n\n\n-=-=-=-=- CONNECTING -=-=-=-=-\n")282 vlc_http_channel = vlc_http(user='', pwd='p1')283 print(type(vlc_http_channel))284 if running_os == 'Linux' and not vlc_http_channel.is_fullscreen():285 print(f"VLC Window detected - going fukll screen")286 vlc_http_channel.toggle_fullscreen()287 print(f"\n-=-=-=-=- CONNECTING -=-=-=-=-\n\n\n")288 # https://pythonise.com/series/learning-flask/flask-and-fetch-api289 if request.method == 'POST':290 print("play_movie: request.method == 'POST'")291 req = request.get_json()292 print(req)293 print('- - - - PLAYING')294 print(f"vlc_http_channel PRESENT?: {type(vlc_http_channel)} <")295 print(f"media file path: { req['path'] } <")296 print(f"file exists: { Path(req['path']).exists() } <")297 if vlc_http_channel != None and Path(req['path']).exists():298 if req['cmd'] == 'start':299 print('--: start: goto begining after opening sequences')300 vlc_http_channel.seek_from_start(210) # got 3m30301 if req['cmd'] == 'bak30s':302 print('--: bak30s')303 vlc_http_channel.seek(-30)304 if req['cmd'] == 'play':305 print('--: play')306 vlc_http_channel.play()307 if req['cmd'] == 'pause':308 print('--: pause')309 vlc_http_channel.pause()310 if req['cmd'] == 'fwd30s':311 print('--: fwd30s')312 vlc_http_channel.seek(30)313# vlc_http_channel.media_length() # length = '5592',314# vlc_http_channel.rate() # rate = '1',315# vlc_http_channel.pos() # position = '0.00087705912301317'316# vlc_http_channel.api_v() # apiversion = '3'317# vlc_http_channel.is_fullscreen() # fullscreen = 'false'318# vlc_http_channel.volume() # volume = '160'319 if req['cmd'] == 'end':320 print('--: end: button Goto END before credits')321 movie_length = vlc_http_channel.media_length()322 near_end_of_flick = movie_length - 360323 vlc_http_channel.seek_from_start(near_end_of_flick) # got end - 6m324 if req['cmd'] == 'bak2x':325 print('--: bak2x - REWIND 120sec')326 vlc_http_channel.seek(-120)327 if req['cmd'] == 'vol':328 # 0-100329 new_vol = int(req['vol'])330 print(f'--: vol:{new_vol}')331 vlc_http_channel.set_volume(new_vol)332 if req['cmd'] == 'fwd2x': # if click second time return to normal speed333 if vlc_http_channel.rate() > 3.5:334 print('--: fwd4x - playback NORMAL')335 vlc_http_channel.set_rate(1)336 else:337 print('--: fwd4x - playback x4')338 vlc_http_channel.set_rate(4.0)339 if req['cmd'] == 's1':340 print('--: s1')341 if req['cmd'] == 's2':342 print('--: s2')343 print(f"CMD: {req['cmd']}")344 #print(f"VOL: {vlc_http_channel.volume()}") # TODO implement functionality345 #print(f"TITLE: {vlc_http_channel.title()}")346 #print(f"FILE: {vlc_http_channel.filename()}")347 #print(f"RATE: {vlc_http_channel.rate()}")348 # print(f"FULLSC:{vlc_http_channel.is_fullscreen()}")349 # secs = int(vlc_http_channel.media_length())350 # m, s = divmod(secs, 60) # / 60 ret div & mod into m, s351 # h, m = divmod(m, 60)352 # print(f"LEN: {secs} - {h}h{m}m")353 # pos = vlc_http_channel.position()354 # pos_secs = int(secs * float(pos))355 # m, s = divmod(pos_secs, 60) # / 60 ret div & mod into m, s356 # h, m = divmod(m, 60)357 # print(f"POS: {pos} - {h}h{m}m")358 #print(f" {vlc_http_channel.}")359 res = make_response(jsonify({"message": "OK"}), 200)360 return res361 else:362 print(f"play_movie: request.method == {request.method}")363 print(f"play_movie: movie ID:{movie_id}")364 info = current_user.info365 pprint(info)366 global users_nav_bar367 return render_template('play_movie.html', movies=movies, prefs_info=info, users_nav_bar=users_nav_bar, page='play_movie')368@app.route('/short_list', methods=["GET", "POST"])369def short_list():370 print(f"\nshort_list: - - - - - - - - debug - - - - - - - - - - - - - - - - S\n")371 if request.method == 'POST':372 if request.is_json:373 print("short_list: request.method == 'POST_JSON'")374 settings = request.get_json() # parse JSON into DICT375 pprint(settings)376 if settings != None and 'mov_id_prefs' in settings:377 print("'mov_prefs' in settings - - - S")378 button = re.sub('mov_prefs_','', settings['button']) # which movie pref button?379 mov_id = settings['mov_id_prefs']380 rating = settings['rating']381 print(f"mov_prefs clicked: {button}")382 if button == 'sl': # REMOVE button383 print(f"short_list: REMOVE - mov_id:{mov_id}")384 print(current_user.info['seen_list'])385 print(current_user.info['short_list'])386 if mov_id in current_user.info['short_list']: current_user.info['short_list'].remove(mov_id)387 commit_dict_to_DB(user_device_DB)388 return json.dumps({}), 201389 elif button == 'rate':390 if (rating != -1) and (mov_id not in current_user.info['ratings']):391 current_user.info['ratings'][mov_id] = rating392 commit_dict_to_DB(user_device_DB)393 return json.dumps({}), 201394 return json.dumps({}), 404395 elif button == 'seen':396 print(f"short_list: seen - mov_id:{mov_id}")397 print(current_user.info['seen_list'])398 print(current_user.info['short_list'])399 if mov_id not in current_user.info['seen_list']: current_user.info['seen_list'].append(mov_id)400 if mov_id in current_user.info['short_list']: current_user.info['short_list'].remove(mov_id)401 commit_dict_to_DB(user_device_DB)402 return json.dumps({}), 201403 print("'mov_prefs' in settings - - - E")404 else:405 print(f"short_list: request.method == {request.method}")406 print(f"\nshort_list: - - - - - - - - debug - - - - - - - - - - - - - - - - E\n")407 movies = media_lib.getMovieShortList(current_user)408 info = current_user.info409 pprint(info)410 title = f"{info['name']}'s movie shortlist"411 return render_template('shortlist.html', movies=movies, prefs_info=info, users_nav_bar=[], title=title, page='short_list')412@app.route('/combined_short_list', methods=["GET", "POST"])413def combined_short_list():414 # filter out duplicates and order most frequent first!415 print("- - - combo SL - - - S")416 if request.method == 'POST':417 if request.is_json:418 print("combined_short_list: request.method == 'POST_JSON'")419 settings = request.get_json() # parse JSON into DICT420 pprint(settings)421 if settings != None and 'mov_id_prefs' in settings:422 button = re.sub('mov_prefs_','', settings['button']) # which movie pref button?423 mov_id = settings['mov_id_prefs']424 if button == 'sl': # REMOVE button425 print(f"combined_short_list: REMOVE - mov_id:{mov_id}")426 for usr_id,usr in user_device_DB.items():427 print(f"u: {usr_id} n:{usr.name} t:{type(usr)} current:{usr.info['current_user']}")428 if mov_id in usr.info['short_list']: usr.info['short_list'].remove(mov_id)429 commit_dict_to_DB(user_device_DB)430 return json.dumps({}), 201431 else:432 print(f"combined_short_list: request.method == {request.method}")433 movies = media_lib.getMovieCombinedList(user_device_DB.values())434 for m in movies:435 #pprint(m)436 print(m['title'])437 print("- - - combo SL - - - E")438 title = "combined movie shortlists"439 return render_template('shortlist.html', movies=movies, prefs_info=[], users_nav_bar=[], title=title, page='combined_short_list')440@app.route('/settings', methods=["GET", "POST"])441def settings():442 info = current_user.info443 pprint(info)444 global users_nav_bar # TODO - investigate propper use of global445 genre_edit = media_lib.genres446 try:447 genre_edit.remove('Adult')448 except Exception:449 pass450 try:451 genre_edit.remove('News')452 except Exception:453 pass454 pprint(genre_edit)455 return render_template('settings.html', prefs_info=info, users_nav_bar=users_nav_bar, genres=genre_edit, page='settings')456@app.route('/spare_route', methods=["GET", "POST"])457def spare_route():458 headline_py = "spare_route"459 movies = []460 return "SPARE route unimplemented <a href='/'>HOME</a>" #render_template('spare_route.html', movies=movies)461if __name__ == '__main__':462 print("Your Computer Name is:" + hostname)463 print("Your Computer IP Address is:" + IPAddr)464 if running_os == 'Darwin' or running_os == 'Linux':465 app.run(host='0.0.0.0', port=52001)466 else:467 print("WARNING unknown host . . . bailing")468 print(f"OS: {running_os} - {running_os_release}")469 sys.exit(0)470 # TODO471 #472 # have a look at source code for https://pypi.org/project/black/473 #474 # Can run as script or module - w/ options475 #476 # > black {source_file_or_directory} # To get started right away with sensible defaults477 #478 # > python -m black {source_file_or_directory} # You can run Black as a package if running it as a script doesn't work:479 #480 #481# EG movie:482# <class 'movie_info_disk.MMdia'>.movie_data483# {'cast': ["Chris Hemsworth",484# <Person id:0788335[http] name:_Michael Shannon_>,485# <Person id:0671567[http] name:_Michael Pena_>,486# .487# .488# <Person id:1041023[http] name:_Navid Negahban_>,489# <Person id:7540945[http] name:_Matthew Velez_>,490# <Person id:8918749[http] name:_Sandra L. Velez_>,491# <Person id:8642817[http] name:_David White_>,492# <Person id:9001165[http] name:_Sarrett Williams_>],493# 'fav': False,494# 'file_name': '12.Strong.2018.1080p.BluRay.mp4',495# 'file_path': PosixPath('/Volumes/FAITHFUL500/15_rpi_shortlist/12 Strong (2018) [BluRay] [1080p]/12.Strong.2018.1080p.BluRay.mp4'),496# 'file_stats': os.stat_result(st_mode=33279, st_ino=29718973, st_dev=16777232, st_nlink=1, st_uid=501, st_gid=20, st_size=4096, st_atime=1593471600, st_mtime=1583265248, st_ctime=1583265248),497# 'file_title': '12 Strong',498# 'genres': ['Action', 'Drama', 'History', 'War'],499# 'hires_image': PosixPath('12_Strong_poster.jpg'),500# 'id': '1413492',501# 'image_url': 'https://m.media-amazon.com/images/M/MV5BNTEzMjk3NzkxMV5BMl5BanBnXkFtZTgwNjY2NDczNDM@._V1_SY150_CR0,0,101,150_.jpg',502# 'kind': 'movie',503# 'movie_data_loaded': True,504# 'rating': 6.6,505# 'runtime_hm': '2h10m',506# 'runtime_m': '130',507# 'seen': False,508# 'synopsis': 'Mitch Nelson, a US Army Captain with Green Berets Operational '509# .510# .511# 'alongside Northern Alliance leader Abdul Rashid Dostum..',512# 'title': '12 Strong',513# 'when_added': None,...

Full Screen

Full Screen

base_utils.py

Source:base_utils.py Github

copy

Full Screen

...402 return results403def pickle_load(filename):404 return pickle.load(open(filename, 'r'))405# Return the kernel version and build timestamp.406def running_os_release():407 return os.uname()[2:4]408def running_os_ident():409 (version, timestamp) = running_os_release()410 return version + '::' + timestamp411def running_os_full_version():412 (version, timestamp) = running_os_release()413 return version414# much like find . -name 'pattern'415def locate(pattern, root=os.getcwd()):416 for path, dirs, files in os.walk(root):417 for f in files:418 if fnmatch.fnmatch(f, pattern):419 yield os.path.abspath(os.path.join(path, f))420def freespace(path):421 """Return the disk free space, in bytes"""422 s = os.statvfs(path)423 return s.f_bavail * s.f_bsize424def disk_block_size(path):425 """Return the disk block size, in bytes"""426 return os.statvfs(path).f_bsize...

Full Screen

Full Screen

sudoers_check.py

Source:sudoers_check.py Github

copy

Full Screen

1#!/usr/bin/python2"""Given an unmodified sudoers (and a sha1 of system python), report on stuff to investigate."""3import hashlib4import platform5def main():6 """gimme some main"""7 clean_sudoers_one = 'bf682f2d93bbcb6465e302fc768646b02c304d40'8 clean_sudoers_two = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'9 clean_python_one = 'ae79a52d9dc6ab37b8dcfc096faf9882ddd12e8e'10 # changed as of 10.10.5+python 2.7.1011 clean_python_two = '46480e019321f49050bbc3c5d087b28d878b6048'12 # if we have a bad sudoers, I want a diff against a 'clean' one13 clean_sudoers_string = """# sudoers file.14 #15 # This file MUST be edited with the 'visudo' command as root.16 # Failure to use 'visudo' may result in syntax or file permission errors17 # that prevent sudo from running.18 #19 # See the sudoers man page for the details on how to write a sudoers file.20 #21 # Host alias specification22 # User alias specification23 # Cmnd alias specification24 # Defaults specification25 Defaults env_reset26 Defaults env_keep += "BLOCKSIZE"27 Defaults env_keep += "COLORFGBG COLORTERM"28 Defaults env_keep += "__CF_USER_TEXT_ENCODING"29 Defaults env_keep += "CHARSET LANG LANGUAGE LC_ALL LC_COLLATE LC_CTYPE"30 Defaults env_keep += "LC_MESSAGES LC_MONETARY LC_NUMERIC LC_TIME"31 Defaults env_keep += "LINES COLUMNS"32 Defaults env_keep += "LSCOLORS"33 Defaults env_keep += "SSH_AUTH_SOCK"34 Defaults env_keep += "TZ"35 Defaults env_keep += "DISPLAY XAUTHORIZATION XAUTHORITY"36 Defaults env_keep += "EDITOR VISUAL"37 Defaults env_keep += "HOME MAIL"38 # Runas alias specification39 # User privilege specification40 root ALL=(ALL) ALL41 %admin ALL=(ALL) ALL42 # Uncomment to allow people in group wheel to run all commands43 # %wheel ALL=(ALL) ALL44 # Same thing without a password45 # %wheel ALL=(ALL) NOPASSWD: ALL46 # Samples47 # %users ALL=/sbin/mount /cdrom,/sbin/umount /cdrom48 # %users localhost=/sbin/shutdown -h now"""49 clean_sudoers_lines = clean_sudoers_string.splitlines()50 # for returning where we had an issue51 baddy_list = []52 running_os_release = '.'.join(platform.mac_ver()[0].split('.')[0:2])53 if running_os_release == '10.10':54 with open('/usr/bin/python', 'rb') as checking_binary:55 actual_python = hashlib.sha1(checking_binary.read()).hexdigest()56 if actual_python != clean_python_one:57 if actual_python != clean_python_two:58 baddy_list.append('Actual python is %s' % actual_python)59 with open('/etc/sudoers', 'rb') as sudoers:60 actual_sudoers = [line.strip() for line in sudoers]61 actual_sudoers_sha = hashlib.sha1(sudoers.read()).hexdigest()62 if actual_sudoers_sha != clean_sudoers_one: 63 if actual_sudoers_sha != clean_sudoers_two:64 diff = []65 for phileline in actual_sudoers:66 if phileline:67 if phileline[0] == '#':68 pass69 else:70 subdline = (' ').join(phileline.split(4*' '))71 if subdline not in clean_sudoers_lines:72 diff.append('\t' + subdline)73 joint_list = '\n'.join(list(diff))74 baddy_list.append('Sudoers is modified, this version has:\n%s' % str(joint_list))75 if baddy_list:76 result = "Caught stuff, investigate: " + "\n".join(*[baddy_list])77 else:78 result = "Not (noticably) pwn3d yet."79 print "<result>%s</result>" % result80if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful