def resolve(self, name): global endpoint_url, put endpoint = endpoint_url + put a = list(filter(lambda x: x in name, self.applist)) if len(a) > 0: self.name = a[0] self.resolve_version(name) if self.name == "eclipse": self.url = "http://archive.eclipse.org/technology/epp/downloads/release/helios/SR2/eclipse-jee-helios-SR2-macosx-cocoa-x86_64.tar.gz" if str(raw_input( 'Do you want to add plugins to the eclipse folder?(Y/n)')).lower() == "y": s = str(raw_input( "Enter the plugin zip URLs separated by commas (,):")) if len(s) > 0: self.extras["plugins"] = s params = {"name": self.name, "version": self.version, "os": utils.get_os(), "arch": utils.get_arch(), "url": self.url} params = dict((k, v) for k, v in params.items() if v.lower() != 'n') response = requests.get( "%s%s" % (endpoint, urllib.urlencode(params))) else: conf_file = os.path.join(os.getcwd(), name, SOFTWARE_CONFIG_NAME) if os.path.isfile(conf_file): con = fetch_conf_dict(conf_file) self.is_custom = True self.custom_conf = con self.name = con['name'] self.version = con['version'] self.url = con['url'] self.cmd = con['cmd'] add_custom_soft_conf(con) params = {"name": self.name, "version": self.version, "os": utils.get_os(), "arch": utils.get_arch(), "command": self.cmd, "url": self.url, "tag": con.get('tag', 'n')} params = dict( (k, v) for k, v in params.items() if v.lower() != 'n') response = requests.get( "%s%s" % (endpoint, urllib.urlencode(params))) else: oscm.call_command('addsoftware') result = None with open("my_file", 'r') as f: try: result = json.load(f) # if the file is empty the ValueError will be thrown except ValueError: result = {} self.is_custom = True self.name = result['name'] self.version = result['version'] self.url = result.get('url', '') self.cmd = result.get('cmd', '')
def media_video(): session['current_video_path'] = session.get('current_video_path') is_admin = session['username'] == "admin" and session['verified'] listFiles = generic_file_listing(path=provide_dir_path(), file_filter=["mp4", "mkv", "webm", "mp3"], view_folder=True if is_admin else False) session['video_list'] = listFiles if session['username'] == "admin": return render_template('streamMedia.html', list=listFiles, dirLength=len(listFiles), drive_name=drives, os_name=get_os()) else: return render_template('streamMedia.html', list=listFiles, dirLength=len(listFiles), drive_name=drives, folders=get_folder_db_data(enable=True), os_name=get_os())
def login(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] if len(email) == 0 or len(password) == 0: flash("email or password is empty") return redirect(request.url) user = get_user_by_email(email) if user is None: flash("user did not exist") elif user.banned: flash("You are Banned") elif user.password == password: session['email'] = email session['username'] = user.user_name session['verified'] = user.verified if user.verified and user.user_name == "admin": session['currentPath'] = drives[0][1] if get_os( ) == 'Linux' else drives[0][0] else: session['currentPath'] = get_folder_db_data( enable=True)[0].folder_path return redirect(url_for('user.index')) else: flash("incorrect username or password ") return redirect(request.url) return render_template('index.html')
def makeFileListRelative(self, relativeFileList, srcFolder, dstFolder): """ Return a list of files with the srcFolder and dstFolder removed from the beginning of the file name. """ srcFolder = os.path.normpath(srcFolder) dstFolder = os.path.normpath(dstFolder) # Make sure there is a trailing slash to make sure the # entire folder name matches platform = utils.get_os() if srcFolder[-1] != '\\': if platform in ('mac', 'linux'): srcFolder += '/' else: srcFolder += '\\' if dstFolder[-1] != '\\': if platform in ('mac', 'linux'): dstFolder += '/' else: dstFolder += '\\' result = [] for path in relativeFileList: # Compare paths using the file systems case sensitivity rel = os.path.normcase(os.path.normpath(path)) rel = rel.replace(os.path.normcase(srcFolder), '') rel = rel.replace(os.path.normcase(dstFolder), '') # Substitute the original path case into the result rel = path[-len(rel):] result.append(rel) return result
def getDstPath(self, relPath): """ Return a full destination path for supplied relative path """ platform = utils.get_os() sep = {'windows': '\\', 'mac': '/', 'linux': '/'}[platform] return os.path.normpath(self.dst + sep + relPath)
def install_packages(self): import params import time distname, version = utils.get_os() major_version = version.split(".")[0] if distname.startswith('ubuntu') or distname.startswith('debian'): cmd = "{sudo} dpkg-query -l | grep 'ii\s*smartsense-*' || {sudo} apt-get -o Dpkg::Options::=--force-confdef --allow-unauthenticated --assume-yes install smartsense-hst || {sudo} dpkg -i " + os.path.join( params.service_package_folder, "files", "deb", "*.deb") elif distname.startswith('sles') or distname.startswith('suse'): cmd = "{sudo} rpm -qa | grep smartsense- || {sudo} zypper install --auto-agree-with-licenses --no-confirm smartsense-hst || {sudo} rpm -i " + os.path.join( params.service_package_folder, "files", "rpm", "*.rpm") else: cmd = "{sudo} rpm -qa | grep smartsense- || {sudo} yum -y install smartsense-hst || {sudo} rpm -i " + os.path.join( params.service_package_folder, "files", "rpm", "*.rpm") print("installing using command: " + cmd) attempts = 0 while attempts < 3: attempts += 1 try: exit_code, output, error = self.execute_command(cmd) if (exit_code == 0): break except Exception, e: print "Failed to install during attempt " % (attempts) print e if (attempts < 3): print "Waiting 5 seconds for next retry" time.sleep(5)
def upgrade_packages(self): import params import time distname, version = utils.get_os() major_version = version.split(".")[0] if distname.startswith('ubuntu') or distname.startswith('debian'): cmd = "{sudo} apt-get -o Dpkg::Options::=--force-confdef --allow-unauthenticated --assume-yes install smartsense-hst" elif distname.startswith('sles') or distname.startswith('suse'): cmd = "{sudo} zypper up --auto-agree-with-licenses --no-confirm smartsense-hst" else: cmd = "{sudo} yum -y upgrade smartsense-hst" print("upgrading using command: " + cmd) attempts = 0 while attempts < MAX_RETRY_ATTEMPTS: attempts += 1 try: exit_code, output, error = self.execute_command(cmd) if (exit_code == 0): break except Exception, e: print "Failed to install during attempt " + str (attempts) print e if (attempts < MAX_RETRY_ATTEMPTS): print "Waiting "+str(WAIT_INTERVAL_SECS)+" seconds for next retry" time.sleep(WAIT_INTERVAL_SECS)
def pack(): dist_dir.parent.mkdir(parents=True, exist_ok=True) dist_file_name = get_dist_name() if os.path.exists(dist_file_name): fsutils.remove(dist_file_name) try: exclude_root = build_config.pack.exclude_root_dir except AttributeError: exclude_root = False if exclude_root: target_dir = '.' cwd = str(get_build_dir()) else: target_dir = get_build_dir() cwd = None if utils.get_os() == 'windows': cmd = "7za a {} {}".format(get_dist_name(), get_build_dir()) else: cmd = "zip -r {} {}".format(get_dist_name(), target_dir) cmd_proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, cwd=cwd) output = cmd_proc.communicate()[0] print(output) if cmd_proc.returncode == 0: print("pack success") else: print("pack failed")
def getSrcPath(self, relPath): """ Return a full source path for supplied relative path """ platform = utils.get_os() sep = {'windows': '\\', 'mac': '/', 'linux': '/'}[platform] return os.path.normpath(self.src + sep + relPath)
def disable_ip_forwarding(): os_platform = utils.get_os() if os_platform == 'mac': cmd = ['/usr/sbin/sysctl', '-w', 'net.inet.ip.forwarding=0'] elif os_platform == 'linux': cmd = ['sysctl', '-w', 'net.ipv4.ip_forward=0'] assert subprocess.call(cmd) == 0
def disable_ip_forwarding(): os_platform = utils.get_os() if os_platform == 'mac': cmd = ['/usr/sbin/sysctl', '-w', 'net.inet.ip.forwarding=0'] elif os_platform == 'linux': cmd = ['sysctl', '-w', 'net.ipv4.ip_forward=0'] elif os_platform == 'windows': cmd = ['powershell', 'Set-NetIPInterface', '-Forwarding', 'Disabled'] assert subprocess.call(cmd) == 0
def uninstall_hst_packages(self): import params distname, version = utils.get_os() removal_command = "" for package in params.smartsense_packages: if distname.startswith('ubuntu') or distname.startswith('debian'): removal_command = '{sudo} ! dpkg-query -l | grep "ii\s*' + package + '" || {sudo} apt-get -y remove ' + package + ' || {sudo} dpkg -r ' + package elif distname.startswith('sles') or distname.startswith('suse'): removal_command = "{sudo} ! rpm -qa | grep " + package + " || {sudo} zypper remove --no-confirm " + package + " || {sudo} rpm -e " + package else: removal_command = "{sudo} ! rpm -qa | grep " + package + " || {sudo} yum -y erase " + package + " || {sudo} rpm -e " + package print("Uninstalling using command: " + removal_command) exit_code, output, error = self.execute_command(removal_command)
def drive(): list_files = generic_file_listing(path=provide_dir_path()) if session['username'] == "admin": return render_template('drive.html', name='FileExplorer', list=list_files, drive_name=drives, os_name=get_os()) else: return render_template('drive.html', name='FileExplorer', list=list_files, drive_name=drives, folders=get_folder_db_data(enable=True))
def download_sec(sec, config_file): v = "0" if config_file.has_option(sec, "version"): v = config_file.get(sec, "version") OS = utils.get_os() arch = utils.get_arch() d = utils.get_info({ "name": sec, "os": OS, "version": v, "arch": arch }) for software in d: if len(software['command']) > 0: subprocess.call(software['command'], shell=True) elif len(software["url"]) > 0: if os.path.isfile(os.path.basename(software["url"])): print 'Downloading ' + sec + '...' r = requests.get(software["url"], stream=True) if r.status_code == 200: with open(os.path.basename(software["url"]), 'wb') as f: for chunk in r: f.write(chunk) if tarfile.is_tarfile(f.name): tfile = tarfile.open( os.path.basename(software["url"]), "r:gz") tfile.extractall(sec) elif zipfile.is_zipfile(f.name): z = zipfile.ZipFile(f) z.extractall(sec) else: print 'Error downloading package, Please download ' + sec + ' on your own!' else: print sec + ' already present in folder, extracting...' print 'Running command ' + str( ['tar', '-xvf', os.path.basename(software["url"])]) subprocess.call(['tar', '-xvf', os.path.basename(software["url"])])
def start(): """ Initializes inspector by spawning a number of background threads. Returns the host state once all background threats are started. """ # Read from home directory the user_key. If non-existent, get one from # cloud. config_dict = utils.get_user_config() utils.log('[MAIN] Starting.') # Set up environment state = HostState() state.user_key = config_dict['user_key'].replace('-', '') state.secret_salt = config_dict['secret_salt'] state.host_mac = utils.get_my_mac() state.gateway_ip, _, state.host_ip = utils.get_default_route() assert utils.is_ipv4_addr(state.gateway_ip) assert utils.is_ipv4_addr(state.host_ip) state.packet_processor = PacketProcessor(state) utils.log('Initialized:', state.__dict__) # Start web API webserver.start_thread(state) # Continously discover devices arp_scan_thread = ArpScan(state) arp_scan_thread.start() # Continously discover ports via SYN scans syn_scan_thread = SynScan(state) syn_scan_thread.start() # Continuously gather SSDP data netdisco_thread = NetdiscoWrapper(state) netdisco_thread.start() # Continuously capture packets packet_capture_thread = PacketCapture(state) packet_capture_thread.start() # Continously spoof ARP if '--no_spoofing' not in sys.argv: arp_spoof_thread = ArpSpoof(state) arp_spoof_thread.start() # Suppress scapy warnings try: logging.getLogger("scapy.runtime").setLevel(logging.ERROR) except Exception: pass # Suppress flask messages try: logging.getLogger('werkzeug').setLevel(logging.ERROR) except Exception: pass # Insert a dash every four characters to make user-key easier to type pretty_user_key = '' for (ix, char) in enumerate(state.user_key): if (ix > 0) and (ix % 4 == 0): pretty_user_key += '-' pretty_user_key += char print('\n' * 100) os_platform = utils.get_os() if os_platform == 'windows': print( WINDOWS_STARTUP_TEXT.format(server_config.BASE_URL, pretty_user_key)) return state
def watch(feed, pid): subtitles_file = None item = iplayer.programme(pid).programme thumbnail = item.programme.thumbnail title = item.programme.title summary = item.programme.summary date = item.programme.date channel = None thumbfile = None if feed and feed.name: channel = feed.name utils.log('watching channel=%s pid=%s' % (channel, pid),xbmc.LOGINFO) utils.log('thumb =%s summary=%s' % (thumbnail, summary),xbmc.LOGINFO) subtitles = get_setting_subtitles() if thumbnail: if feed is not None and pid == feed.channel: # Listening to a live radio station, use the pre-downloaded file thumbfile = get_feed_thumbnail(feed) else: # attempt to use the existing thumbnail file thumbcache = xbmc.getCacheThumbName( sys.argv[ 0 ] + sys.argv[ 2 ] ) if utils.get_os() == "xbox": thumbfile = os.path.join( xbmc.translatePath( "special://profile" ), "Thumbnails", "Video", thumbcache[ 0 ], thumbcache ) else: thumbfile = os.path.join( xbmc.translatePath( "special://profile" ), "Thumbnails", thumbcache[ 0 ], thumbcache ) utils.log('Reusing existing thumbfile=%s for url %s%s' % (thumbfile, sys.argv[ 0 ], sys.argv[ 2 ]),xbmc.LOGINFO) if thumbnail and not os.path.isfile(thumbfile): # thumbnail wasn't available locally so download try: # The thumbnail needs to accessed via the local filesystem # for "Media Info" to display it when playing a video iplayer.httpretrieve(thumbnail, thumbfile) except: pass if item.is_tv and item.is_live: (media_list, above_limit) = item.get_available_streams_live() else: (media_list, above_limit) = item.get_available_streams() if len(media_list) == 0: # Nothing usable was found d = xbmcgui.Dialog() d.ok('Stream Error', 'Can\'t locate any usable streams.') return False for media in media_list: player = None listitem = xbmcgui.ListItem(label=title) if item.is_tv: # TV Stream iconimage = 'DefaultVideo.png' if above_limit: d = xbmcgui.Dialog() if d.yesno('Default Stream Not Available', 'Play higher bitrate stream?') == False: return False url = media.url utils.log('watching url=%s' % url,xbmc.LOGINFO) if subtitles: subtitles_media = item.get_media_list_for('captions', None) if subtitles_media and len(subtitles_media) > 0: subtitles_file = download_subtitles(subtitles_media[0].url) if not item.live: listitem.setInfo('video', { "TVShowTitle": title, 'Plot': summary + ' ' + date, 'PlotOutline': summary,}) play=xbmc.PlayList(xbmc.PLAYLIST_VIDEO) else: if not media: d = xbmcgui.Dialog() d.ok('Stream Error', 'Error: can\'t locate radio stream') return False if media.application in ['wma9', 'wma+asx']: url = parse_asx(media.url) else: url = media.url utils.log('Listening to url=%s' % url,xbmc.LOGINFO) listitem.setInfo(type='Music', infoLabels = {'title': title}) listitem.setIconImage('defaultAudio.png') utils.log('Playing preference %s %s' % (media.connection_kind, media.application),xbmc.LOGINFO) if thumbfile: listitem.setIconImage(thumbfile) listitem.setThumbnailImage(thumbfile) listitem.setPath(url) xbmcplugin.setResolvedUrl(__plugin_handle__, succeeded = True, listitem = listitem) xbmc.sleep(500) # Successfully started playing something? if xbmc.Player().isPlaying(): break; # Auto play subtitles if they have downloaded utils.log("subtitles: %s - subtitles_file %s " % (subtitles,subtitles_file),xbmc.LOGINFO) if subtitles == 'autoplay' and subtitles_file: xbmc.Player().setSubtitles(subtitles_file) if not item.is_tv: # Switch to a nice visualisation if playing a radio stream xbmc.executebuiltin('ActivateWindow(Visualisation)') del item
def get_thumb_dir(): thumb_dir = os.path.join(__addoninfo__['path'], 'resources', 'media') if utils.get_os() == "xbox": thumb_dir = os.path.join(thumb_dir, 'xbox') return thumb_dir
def start(): """ Initializes inspector by spawning a number of background threads. Returns the host state once all background threats are started. """ # Read from home directory the user_key. If non-existent, get one from # cloud. config_dict = utils.get_user_config() utils.log('[MAIN] Starting.') # Set up environment state = HostState() state.user_key = config_dict['user_key'].replace('-', '') state.secret_salt = config_dict['secret_salt'] state.host_mac = utils.get_my_mac() state.gateway_ip, _, state.host_ip = utils.get_default_route() # Read special command-line arguments if '--raspberry_pi_mode' in sys.argv: state.raspberry_pi_mode = True assert utils.is_ipv4_addr(state.gateway_ip) assert utils.is_ipv4_addr(state.host_ip) state.packet_processor = PacketProcessor(state) utils.log('Initialized:', state.__dict__) # Continously discover devices arp_scan_thread = ArpScan(state) arp_scan_thread.start() # Continously discover ports via SYN scans syn_scan_thread = SynScan(state) syn_scan_thread.start() # Continuously gather SSDP data netdisco_thread = NetdiscoWrapper(state) netdisco_thread.start() # Continuously capture packets packet_capture_thread = PacketCapture(state) packet_capture_thread.start() # Continously spoof ARP if '--no_spoofing' not in sys.argv: arp_spoof_thread = ArpSpoof(state) arp_spoof_thread.start() # Continuously upload data data_upload_thread = DataUploader(state) data_upload_thread.start() # Suppress scapy warnings try: logging.getLogger("scapy.runtime").setLevel(logging.ERROR) except Exception: pass # Suppress flask messages try: logging.getLogger('werkzeug').setLevel(logging.ERROR) except Exception: pass # Insert a dash every four characters to make user-key easier to type pretty_user_key = '' for (ix, char) in enumerate(state.user_key): if (ix > 0) and (ix % 4 == 0): pretty_user_key += '-' pretty_user_key += char print('\n' * 100) os_platform = utils.get_os() print(WINDOWS_STARTUP_TEXT.format(server_config.BASE_URL, pretty_user_key)) # Open a browser window on Windows 10. Note that a new webpage will be # opened in a non-privileged mode. TODO: Not sure how to do the same # for macOS, as the "open" call on macOS will open a browser window # in privileged mode. if os_platform == 'windows': utils.open_browser_on_windows('{0}/user/{1}'.format( server_config.BASE_URL, pretty_user_key)) return state
def parse_config(config_file): secs = config_file.sections() v = "0" for sec in secs: if config_file.has_option(sec, "version"): v = config_file.get(sec, "version") OS = utils.get_os() arch = utils.get_arch() d = utils.get_info({ "name": sec, "os": OS, "version": v, "arch": arch }) print d, str({"name": sec, "os": OS, "version": v, "arch": arch}) for software in d: if len(software.get('command', '')) > 0: subprocess.call(software['command'], shell=True) elif len(software["url"]) > 0: print software["url"] if not os.path.isfile(os.path.basename(software["url"])): print 'Downloading ' + sec + '...' r = requests.get(software["url"], stream=True) if r.status_code == 200: with open(os.path.basename(software["url"]), 'wb') as f: for chunk in r: f.write(chunk) # if tarfile.is_tarfile(f.name): # tfile = tarfile.open(os.path.basename(software["url"]), "r:gz") # tfile.extractall(sec) # elif zipfile.is_zipfile(f.name): # z = zipfile.ZipFile(f) # z.extractall(sec) subprocess.call('tar -xvf ' + f.name, shell=True) else: print 'Error downloading package, Please download ' + sec + ' on your own!' else: print sec + ' already present in folder, extracting...' subprocess.call('tar -xvf ' + os.path.basename(software["url"]), shell=True) # if tarfile.is_tarfile(os.path.basename(software["url"])): # tfile = tarfile.open(os.path.basename(software["url"]), "r:gz") # tfile.extractall(sec) # elif zipfile.is_zipfile(os.path.basename(software["url"])): # z = zipfile.ZipFile(os.path.basename(software["url"])) # z.extractall(sec) if not os.path.exists(sec): os.mkdir(sec) if sec == 'eclipse': if config_file.has_option(sec, "plugins"): plugins = config_file.get(sec, "plugins").split(",") if os.path.isdir(os.path.join(os.getcwd(), sec, "dropins")): for plugin in plugins: f = download_file(plugin) if len(f) > 0 and zipfile.is_zipfile(f): z = zipfile.ZipFile(open(f, "rb")) path = os.path.join(os.getcwd(), "eclipse", "dropins", os.path.splitext(f)[0]) if not os.path.exists(path): os.makedirs(path) z.extractall(path)
def install_activity_analyzer(self): import params import grp if 'ignore_groupsusers_create' in params.config['configurations'][ 'cluster-env']: print( 'ignore_groupsusers_create', params.config['configurations'] ['cluster-env']['ignore_groupsusers_create']) if 'ignore_groupsusers_create' in params.config['configurations'][ 'cluster-env'] and ( params.config['configurations']['cluster-env'] ['ignore_groupsusers_create'] == True or str(params.config['configurations']['cluster-env'] ['ignore_groupsusers_create']).lower() == 'true'): print( "Skipping activity analyzer user creation as specified by ambari config 'ignore_groupsusers_create'. Please make sure following user is created on NameNode." ) print( "User Id: " + params.config['configurations']['activity-conf'] ['global.activity.analyzer.user'] + "; group : " + params.config['configurations']['cluster-env']['user_group']) else: if 'hadoop-env' in params.config[ 'configurations'] and 'hdfs_user' in params.config[ 'configurations']['hadoop-env']: try: g = grp.getgrnam(params.config['configurations'] ['hadoop-env']['hdfs_user']) User(params.config['configurations']['activity-conf'] ['global.activity.analyzer.user'], gid=params.config['configurations']['cluster-env'] ['user_group'], groups=params.config['configurations']['hadoop-env'] ['hdfs_user']) print( "Created user with additional group " + str(params.config['configurations']['hadoop-env'] ['hdfs_user'])) except KeyError: User(params.config['configurations']['activity-conf'] ['global.activity.analyzer.user'], gid=params.config['configurations']['cluster-env'] ['user_group']) print( "Created user without additional group " + str(params.config['configurations']['hadoop-env'] ['hdfs_user'])) else: User(params.config['configurations']['activity-conf'] ['global.activity.analyzer.user'], gid=params.config['configurations']['cluster-env'] ['user_group']) print("Created user without hdfs group ") user, group = self.get_owner_user_and_group() init_d_dir = "/etc/rc.d/init.d" distname, version = utils.get_os() if distname.startswith('sles') or distname.startswith('suse'): init_d_dir = "/etc/init.d" cmd = "{sudo} /usr/sbin/hst activity-analyzer setup " + user + ":" + group + " '" + init_d_dir + "'" print("Deploying activity analyzer") exit_code, output, error = self.execute_command(cmd)
def main(): sc.load_layer("http") # The whole process should be run as root. try: is_admin = os.getuid() == 0 except AttributeError: is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0 if not is_admin: sys.stderr.write('Please run as root.\n') sys.exit(1) # Check for Windows if utils.get_os() == 'windows': # Check Npcap installation npcap_path = os.path.join(os.environ['WINDIR'], 'System32', 'Npcap') if not os.path.exists(npcap_path): sys.stderr.write( "IoT Inspector cannot run without installing Npcap.\n") sys.stderr.write("For details, visit " + server_config.NPCAP_ERROR_URL) utils.open_browser_on_windows(server_config.NPCAP_ERROR_URL) sys.exit(1) # Check presence of multiple interfaces (e.g., VPN) if len(utils.get_network_ip_range()) == 0: sys.stderr.write( "IoT Inspector cannot run with multiple network interfaces running.\n" ) sys.stderr.write("For details, visit " + server_config.NETMASK_ERROR_URL) utils.open_browser_on_windows(server_config.NETMASK_ERROR_URL) sys.exit(1) utils.log('[Main] Terminating existing processes.') if not kill_existing_inspector(): utils.log('[Main] Unable to end existing process. Exiting.') return utils.log('[Main] Starting inspector.') inspector.enable_ip_forwarding() # We don't wrap the function below in safe_run because, well, if it crashes, # it crashes. host_state = inspector.start() # Waiting for termination while True: with host_state.lock: if host_state.quit: break try: time.sleep(2) except KeyboardInterrupt: print('') break utils.log('[Main] Restoring ARP...') with host_state.lock: host_state.spoof_arp = False for t in range(10): print('Cleaning up ({})...'.format(10 - t)) time.sleep(1) inspector.disable_ip_forwarding() utils.log('[Main] Quit.') print('\n' * 100) print(""" Princeton IoT Inspector has terminated. Feel free to close this window. """) # Remove PID file try: os.remove(get_pid_file()) except Exception: pass
def __init__(self, host_state): self._host_state = host_state self._os = utils.get_os() self._netdisco_path = self._get_netdisco_path()
def watch(feed, pid): subtitles_file = None item = iplayer.programme(pid).programme thumbnail = item.programme.thumbnail title = item.programme.title summary = item.programme.summary date = item.programme.date channel = None thumbfile = None if feed and feed.name: channel = feed.name utils.log('watching channel=%s pid=%s' % (channel, pid), xbmc.LOGINFO) utils.log('thumb =%s summary=%s' % (thumbnail, summary), xbmc.LOGINFO) subtitles = get_setting_subtitles() if thumbnail: if feed is not None and pid == feed.channel: # Listening to a live radio station, use the pre-downloaded file thumbfile = get_feed_thumbnail(feed) else: # attempt to use the existing thumbnail file thumbcache = xbmc.getCacheThumbName(sys.argv[0] + sys.argv[2]) if utils.get_os() == "xbox": thumbfile = os.path.join( xbmc.translatePath("special://profile"), "Thumbnails", "Video", thumbcache[0], thumbcache) else: thumbfile = os.path.join( xbmc.translatePath("special://profile"), "Thumbnails", thumbcache[0], thumbcache) utils.log( 'Reusing existing thumbfile=%s for url %s%s' % (thumbfile, sys.argv[0], sys.argv[2]), xbmc.LOGINFO) if thumbnail and not os.path.isfile(thumbfile): # thumbnail wasn't available locally so download try: # The thumbnail needs to accessed via the local filesystem # for "Media Info" to display it when playing a video iplayer.httpretrieve(thumbnail, thumbfile) except: pass if item.is_tv and item.is_live: (media_list, above_limit) = item.get_available_streams_live() else: (media_list, above_limit) = item.get_available_streams() if len(media_list) == 0: # Nothing usable was found d = xbmcgui.Dialog() d.ok('Stream Error', 'Can\'t locate any usable streams.') return False for media in media_list: player = None listitem = xbmcgui.ListItem(label=title) if item.is_tv: # TV Stream iconimage = 'DefaultVideo.png' if above_limit: d = xbmcgui.Dialog() if d.yesno('Default Stream Not Available', 'Play higher bitrate stream?') == False: return False url = media.url utils.log('watching url=%s' % url, xbmc.LOGINFO) if subtitles: subtitles_media = item.get_media_list_for('captions', None) if subtitles_media and len(subtitles_media) > 0: subtitles_file = download_subtitles(subtitles_media[0].url) if not item.live: listitem.setInfo( 'video', { "TVShowTitle": title, 'Plot': summary + ' ' + date, 'PlotOutline': summary, }) play = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) else: if not media: d = xbmcgui.Dialog() d.ok('Stream Error', 'Error: can\'t locate radio stream') return False if media.application in ['wma9', 'wma+asx']: url = parse_asx(media.url) else: url = media.url utils.log('Listening to url=%s' % url, xbmc.LOGINFO) listitem.setInfo(type='Music', infoLabels={'title': title}) listitem.setIconImage('defaultAudio.png') utils.log( 'Playing preference %s %s' % (media.connection_kind, media.application), xbmc.LOGINFO) if thumbfile: listitem.setIconImage(thumbfile) listitem.setThumbnailImage(thumbfile) listitem.setPath(url) xbmcplugin.setResolvedUrl(__plugin_handle__, succeeded=True, listitem=listitem) xbmc.sleep(500) # Successfully started playing something? if xbmc.Player().isPlaying(): break # Auto play subtitles if they have downloaded utils.log( "subtitles: %s - subtitles_file %s " % (subtitles, subtitles_file), xbmc.LOGINFO) if subtitles == 'autoplay' and subtitles_file: xbmc.Player().setSubtitles(subtitles_file) if not item.is_tv: # Switch to a nice visualisation if playing a radio stream xbmc.executebuiltin('ActivateWindow(Visualisation)') del item