Created
March 30, 2012 01:12
-
-
Save jamak/2245492 to your computer and use it in GitHub Desktop.
help me work
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
#!/usr/bin/env python | |
#Work.py -- a short python script to keep me from getting sidetracked | |
import getpass | |
import sys | |
import subprocess | |
from flask import Flask | |
hostfile = '/etc/hosts' | |
restartNetworkingCommand = ["dscacheutil", "-flushcache"] | |
blacklist = ("reddit.com", "facebook.com", "news.ycombinator.com", "hackerne.ws", | |
"arstechnica.com", "avclub.com", "plus.google.com", "tumblr.com", "cracked.com", | |
"engadget.com", "jezebel.com") | |
workhome = "dowork.html" | |
payload = [] | |
start_token = "## start-working" | |
end_token = "## end-working" | |
class ExitError(Exception): | |
def __init__(self, msg): | |
self.msg = msg | |
def restart(): | |
"""restarts the networking interface""" | |
subprocess.call(restartNetworkingCommand) | |
return | |
def start(): | |
with open(hostfile, 'a+') as hfile: | |
contents = hfile.readlines() | |
contents = [r.strip() for r in contents] | |
if start_token in contents and end_token in contents: | |
raise ExitError("Work mode already set") | |
else: | |
payload.append(start_token + "\n") | |
for site in blacklist: | |
payload.append("127.0.0.1\t" + site + "\n") | |
payload.append("127.0.0.1\twww." + site + "\n") | |
payload.append(end_token) | |
d = [hfile.write(x) for x in payload] | |
restart() | |
return | |
def stop(): | |
hfile = open(hostfile, "r+") | |
lines = hfile.readlines() | |
start_index = -1 | |
for index, line in enumerate(lines): | |
if line.strip() == start_token: | |
start_index = index | |
if start_index > -1: | |
lines = lines[0:start_index] | |
hfile.seek(0) | |
hfile.write(''.join(lines)) | |
hfile.truncate() | |
restart() | |
app = Flask(__name__) | |
@app.route("/") | |
def serve(): | |
return "<h1>GET BACK TO WORK</h1>" | |
def main(): | |
if getpass.getuser() is 'root': | |
raise ExitError('Please run script as root.') | |
if len(sys.argv) != 2: | |
ExitError('usage: ' + sys.argv[0] + '[start|stop]') | |
if sys.argv[1] == "start": | |
start() | |
app.run(host='127.0.0.1', port=80) | |
elif sys.argv[1] == "stop": | |
stop() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment