import os
import redis
import sys

def run_p0f():
    os.system('/usr/bin/p0f -r ' + sys.argv[1] + ' -o /tmp/output.txt > /dev/null')
    return

def parse_output():
    results = {}
    with open('/tmp/output.txt', 'r') as f:
        for line in f:
            l = " ".join(line.split()[2:])
            l = l.split('|')
            if l[0] == 'mod=syn':
                results[l[1].split('cli=')[1].split('/')[0]] = {'full_os': l[4].split('os=')[1], 'short_os': l[4].split('os=')[1].split()[0]}
    return results

def connect():
    r = None
    try:
        r = redis.StrictRedis(host='redis', port=6379, db=0)
    except Exception as e:  # pragma: no cover
        try:
            r = redis.StrictRedis(host='localhost', port=6379, db=0)
        except Exception as e:  # pragma: no cover
            return (False, 'unable to connect to redis because: ' + str(e))
    return r

def save(r, results):
    if r:
        try:
            r.hmset('foo', results)
        except Exception as e:  # pragma: no cover
            return (False,
                    'unable to store contents of the p0f [ ' +
                    str(results) + ' ] in redis because: ' +
                    str(e))
    return

def main():
    run_p0f()
    results = parse_output()
    print results
    r = connect()
    save(r, results)
    return

if __name__ == "__main__":
    main()

@@ -805,23 +805,14 @@
     
-return (False, 
+print(
 'una
@@ -907,32 +907,68 @@
 r:%0A        try:%0A
+            for key in results:%0A    
             r.hm
@@ -975,13 +975,11 @@
 set(
-'foo'
+key
 , re
@@ -979,24 +979,29 @@
 key, results
+%5Bkey%5D
 )%0A        ex
@@ -1057,43 +1057,14 @@
     
-return (False,%0A                    
+print(
 'una
@@ -1097,29 +1097,40 @@
 he p0f %5B ' +
-%0A    
+ str(results) +%0A
             
@@ -1133,30 +1133,17 @@
         
-str(results) +
+ 
  ' %5D in 
@@ -1164,28 +1164,8 @@
  ' +
-%0A                   
  str
@@ -1245,24 +1245,25 @@
    print
- 
+(
 results
+)
 %0A    r =

store results by ip