def host(args): db = get_db(args) ipaddr = args.ipaddress[0] hostinfo = [] if args.mac: addrinfo = db.macaddr.find_one({"address": ipaddr}) if addrinfo is not None: hostinfo = [addrinf["host"]] else: addrinfo = db.v4addr.find_one({"address": ipaddr}) if addrinfo is not None: hostinfo = addrinfo["hosts"] hostinfo = [deref(db, h) for h in hostinfo] if args.snmp: hostinfo = [db.snmp.find_one({"ident": h["ident"]}) for h in hostinfo] elif args.login: hostinfo = [db.login.find_one({"ident": h["ident"]}) for h in hostinfo] if args.json: for h in hostinfo: h["_id"] = str(h["_id"]) print json.dumps(hostinfo) elif args.pprint: for host in hostinfo: if host is not None: pprint(host) else: for host in hostinfo: if host is not None: hprint(db, host)
def auth(args): if (args.username and not args.password) or \ (not args.username and args.password): sys.stderr.write("Error: both username and password must be specified\n") return db = get_db(args) authinfo = db.authinfo.find_one({"name": args.name}) if authinfo is None: authinfo = {"name": args.name} if args.show: pprint(authinfo) elif args.add: if args.community is not None: clist = authinfo.get("community", []) clist.append(args.community) authinfo["community"] = list(set(clist)) if args.username is not None: uplist = [tuple(x) for x in authinfo.get("login", [])] uplist.append((args.username, args.password)) authinfo["login"] = list(set(uplist)) db.authinfo.save(authinfo) elif args.replace: if args.community is not None: authinfo["community"] = [args.community] if args.username is not None: authinfo["login"] = [(args.username, args.password)] db.authinfo.save(authinfo) elif args.delete: db.authinfo.remove(authinfo) else: args.parser.print_help()
def oauth(args): db = get_db(args) site = db.oauth.find_one({ "name": [args.site_name] }) if site is None: site = {} site["name"] = args.site_name[0] site["client_id"] = args.client_id[0] site["client_secret"] = args.client_secret[0] site["oauth_url"] = args.oauth_url[0] db.oauth.save(site)
def serve(args): from werkzeug.serving import run_simple from server import TegolaRest db = get_db(args) app = TegolaRest(db, mountpoint=args.mountpoint) if args.socket: from flup.server.fcgi import WSGIServer WSGIServer(app, bindAddress=args.socket).run() else: run_simple(args.listen, args.port, app, use_debugger=args.debug, use_reloader=args.debug)
def get(self, uid, pid): try: self.uid = int(uid) self.pid = int(pid) except: self.send_error(404) return if self.pid > len(styles): self.pid = 0 self.cache = False self.db = storage.get_db('signature') self.db.signature.find_one({'_id':self.uid}, callback = self.got_setting)
def spectrum(args): db = get_db(args) if args.frequency is not None: if not args.frequency.endswith("GHz"): args.frequency = args.frequency + " GHz" info = freqinfo(db, args.frequency) freqs = info.keys() freqs.sort() for f in freqs: print f freqlist = info[f] for host in freqlist: print "\t%(ssid)-30s s%(mac)s %(name)s (%(iface)s)" % host
def _db_search(search_form, **kwargs): db = get_db() query = search_form.value text_str = (query.pop('text') or u"").strip() if any(text_str.startswith(ch) for ch in ['*', '?']): # the Solr QueryParser does not accept leading-wildcard queries raise SearchError(u"Textul nu poate să înceapă cu '*' sau '?'") text = AllowWildcards(text_str) text_or = Or([('name', text), ('text', text)]) full_query = And([text_or, query]) try: return db.search(full_query, **kwargs) except StorageError, e: raise SearchError(u"Eroare bază de date: %s" % e)
def route(args): db = get_db(args) quarantine = ip.ip_network(args.quarantine) routes = set([]) for host in db.hosts.find({}, {"v4routes":1}): for route in host.get("v4routes", []): network = ip.ip_network(route["network"]) if network.network_address in quarantine: routes.add(network) routes = list(routes) routes.sort() ## remove supernets... this is a bit weird... def supernets(n): s = n.supernet() if s == n: return yield s for s in supernets(s): yield s ## hella ineffient prune = set([]) for r in routes: ## except interface routes... if r.prefixlen == 32: continue for s in supernets(r): prune.add(s) for p in prune: if p in routes: routes.remove(p) addrs = set([]) for addr in db.v4addr.find(): addrs.add(ip.ip_address(addr["address"])) addrs = list(addrs) addrs.sort() for r in routes: print r for addr in addrs: if addr in r: hinfo = gethostbyv4addr(db, addr) for host in hinfo: print "\t%-16s%s" % (addr, host["name"])
def get(self, uid, pid): try: self.uid = int(uid) self.pid = int(pid) except: self.send_error(404) return # 容错处理 # 0-5 if self.pid < 0 and self.pid >= len(background_image): self.pid = 0 self.cache = False self.db = storage.get_db('signature') # self.db.signature.find_one({'_id':self.uid}, callback = self.got_setting) self.got_setting(None, False)
def interrogate(args): db = get_db(args) hostname = args.hostname[0] authinfo = db.authinfo.find_one({"name": hostname}) if authinfo is None: authinfo = {"name": hostname} default = db.authinfo.find_one({"name": "default"}) if default is None: authinfo = {} descriptions = {} if args.snmp: for community in authinfo.get("community", []) + default.get("community", []): log.info("querying with SNMP community: %s" % community) try: from snmp import interrogate_snmp descriptions["snmp"] = interrogate_snmp(hostname, community=community) authinfo["community"] = [community] break except: pass if args.login: for u,p in authinfo.get("login", []) + default.get("login", []): log.info("logging in as user: %s" % u) try: from rlogin import interrogate_rlogin descriptions["login"] = interrogate_rlogin(host=hostname, username=u, password=p) authinfo["login"] = [(u,p)] break except: pass db.authinfo.save(authinfo) try: ident = pkey_check(descriptions) except PKeyError, e: log.warning("%s\n%s" % (e, format_exc(e))) return
def view(): doc_id = flask.request.args.get('doc_id') db = get_db() try: doc = db.load_document(doc_id) except NotFound: flask.abort(404) form = widgets.MarkupGenerator(flask.current_app.jinja_env) form.other_site_labels = _other_site_labels(doc) options = { 'title': _doc_title(doc), 'form': form, 'doc_id': doc_id, 'doc': doc, } app = flask.current_app if 'PDF_URL' in app.config: pdf_name = doc_id.lower() + '.pdf' options['pdf_url'] = app.config['PDF_URL'] + pdf_name return flask.render_template('view.html', **options)
def annotate(args): db = get_db(args) hostname = args.hostname[0] authinfo = db.authinfo.find_one({"name": hostname}) if authinfo is None or authinfo.get("login") is None: log.error("Do not have a username for this host, interrogate it first, please") return hinfo = gethostbyv4addr(db, hostname) if hinfo is None: hinfo = gethostbymacaddr(db, hostname) if hinfo is None: log.error("Interrogate this host first, please") return elif len(hinfo) == 1: hinfo = hinfo[0] elif len(hinfo) > 1: log.error("Several matching hosts found:") for h in hinfo: log.error(" %s" % h["ident"]) log.error("Try using the identifier instead.") annotations = db.annotations.find_one({ "ident": hinfo["ident"]}) if annotations is None: annotations = { "ident": hinfo["ident"] } if args.json: value = json.loads(args.value[0]) else: value = args.value[0] if args.key[0] in annotations and not value: del annotations[args.key[0]] else: annotations[args.key[0]] = value db.annotations.save(annotations) merge_host(db, hinfo["ident"])
def _other_site_labels(doc): db = get_db() other_site_ids = Or(o.value for o in doc['section1']['other_sites']) results = db.search({'id': other_site_ids}) return dict((data['id'], data['name']) for data in results['docs'])
def dump(): db = get_db() docs = db.search({}, get_data=True)['docs'] return flask.jsonify(dict((d['id'], d['data']) for d in docs))
def config(args): db = get_db(args) hostname = args.hostname[0] authinfo = db.authinfo.find_one({"name": hostname}) if authinfo is None or authinfo.get("login") is None: log.error("Do not have a username for this host, interrogate it first, please") return hinfo = gethostbyv4addr(db, hostname) if hinfo is None: hinfo = gethostbymacaddr(db, hostname) if hinfo is None: log.error("Interrogate this host first, please") return elif len(hinfo) == 1: hinfo = hinfo[0] elif len(hinfo) > 1: log.error("Several matching hosts found:") for h in hinfo: log.error(" %s" % h["ident"]) log.error("Try using the identifier instead.") import os, os.path def trymkdir(d): try: os.stat(d) except OSError: os.makedirs(d) if isinstance(args.path, list): cfgpath = args.path[0] else: cfgpath = args.path trymkdir(cfgpath) ### XXXX should be in the database! dontuse = [ip.ip_address(a) for a in ("10.10.10.10", "10.127.127.10", "10.123.123.123")] mgmtnet = ip.ip_network("10.0.0.0/8") def getaddr(hinfo): for iface in hinfo.get("interfaces", []): for ifa in [ip.ip_interface(a) for a in iface.get("v4addr", [])]: if ifa.ip in mgmtnet and ifa.ip not in dontuse: return ifa.ip from rlogin import Rcmd import pexpect if hinfo.get("flavour") is None: log.warning("[%(name)s] Couldn't determine which OS variant to use for backing up, sorry." % hinfo) elif hinfo["flavour"].lower() == "openwrt" or hinfo["flavour"] == "NanoBSD": cfgpath = os.path.join(cfgpath, hinfo["ident"]) trymkdir(cfgpath) c = Rcmd(host=getaddr(hinfo), path=cfgpath, username=authinfo["login"][0][0], password=authinfo["login"][0][1], cmd="sh -c 'ssh %(username)s@%(host)s tar -cf - /etc | (cd %(path)s; tar -xf -)'", timeout=300) try: c.run() except pexpect.EOF: pass elif hinfo["flavour"] == "AirOS": cfgpath = os.path.join(cfgpath, hinfo["ident"]) + ".cfg" c = Rcmd(host=getaddr(hinfo), path=cfgpath, username=authinfo["login"][0][0], password=authinfo["login"][0][1], cmd="scp -q -r %(username)s@%(host)s:/tmp/system.cfg %(path)s", timeout=300) try: c.run() except pexpect.EOF: pass else: log.warning("[%(name)s] don't know how to back up the config of a %(flavour)s host" % hinfo) return log.info("[%(name)s] done." % hinfo)
############## ### Shoreditch Gamerunner ############## from bottle import run from handlers import * from config import PORT from storage import get_db from preload_ais import AI from util import add_player db = get_db() for ai in AI: add_player(db, AI[ai][0], AI[ai][1], ai) run(host='localhost', port=PORT, reloader=True)