Last active
January 10, 2018 16:22
-
-
Save ryanpeach/2990c6f98de3ea0f7909d3d39d971a84 to your computer and use it in GitHub Desktop.
Using wmctrl in Linux, close any windows who's titles are not recognized via a whitelist (with regex).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import subprocess | |
import re | |
def get_windows(): | |
list_of_windows = subprocess.check_output(["wmctrl","-l"]).split(b"\n") | |
meta_list_of_windows = [s.decode("utf-8").split() for s in list_of_windows if s] | |
user_processes = {} | |
for line in meta_list_of_windows: | |
n = int(line[1]) | |
if n == 0: | |
user_processes[line[0]] = " ".join(line[3:]) | |
return user_processes | |
def close_window(title): | |
return subprocess.call(["wmctrl","-c",title]) | |
def get_whitelist(fname): | |
patterns = [] | |
with open(fname, "r") as f: | |
for line in f: | |
patterns.append(re.compile(line.replace("\n",""))) | |
return patterns | |
if __name__=="__main__": | |
import argparse | |
# Get arguments from user | |
parser = argparse.ArgumentParser(description="Using wmctrl in Linux, close any windows who's titles are not recognized via a whitelist (with regex).") | |
# Plotting Options | |
parser.add_argument('-f', '--fname', metavar='f', type=str, default="./whitelist.conf", | |
help='The file name and path of the whitelist.') | |
args = parser.parse_args() | |
user_processes = get_windows() | |
whitelist = get_whitelist(args.fname) | |
allowed = set() | |
for pattern in whitelist: | |
for k, v in user_processes.items(): | |
if re.fullmatch(pattern, v) is not None: | |
allowed.add(k) | |
disallowed = set(user_processes.keys()) - allowed | |
for k in disallowed: | |
close_window(user_processes[k]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment