common.py revision 6e1919c3
1import os
2import sys
3import string
4import random
5import time
6import socket
7import re
8
9try:
10    import pwd
11except ImportError:
12    import getpass
13    pwd = None
14
15using_python_3 = True if sys.version_info.major == 3 else False
16
17def get_current_user():
18  if pwd:
19      return pwd.getpwuid(os.geteuid()).pw_name
20  else:
21      return getpass.getuser()
22
23
24def user_input():
25    if using_python_3:
26        return input()
27    else:
28        # using python version 2
29        return raw_input()
30
31
32class random_id_gen:
33    """
34    Emulated generator for creating a random chars id of specific length
35
36    :parameters:
37        length : int
38            the desired length of the generated id
39
40            default: 8
41
42    :return:
43        a random id with each next() request.
44    """
45    def __init__(self, length=8):
46        self.id_chars = string.ascii_lowercase + string.digits
47        self.length = length
48
49    def next(self):
50        return ''.join(random.choice(self.id_chars) for _ in range(self.length))
51
52    __next__ = next
53
54
55# try to get number from input, return None in case of fail
56def get_number(input):
57    try:
58        return long(input)
59    except:
60        try:
61            return int(input)
62        except:
63            return None
64
65def list_intersect(l1, l2):
66    return list(filter(lambda x: x in l2, l1))
67
68def list_difference (l1, l2):
69    return list(filter(lambda x: x not in l2, l1))
70
71def is_sub_list (l1, l2):
72    return set(l1) <= set(l2)
73
74# a simple passive timer
75class PassiveTimer(object):
76
77    # timeout_sec = None means forever
78    def __init__ (self, timeout_sec):
79        if timeout_sec != None:
80            self.expr_sec = time.time() + timeout_sec
81        else:
82            self.expr_sec = None
83
84    def has_expired (self):
85        # if no timeout was set - return always false
86        if self.expr_sec == None:
87            return False
88
89        return (time.time() > self.expr_sec)
90
91def is_valid_ipv4 (addr):
92    try:
93        socket.inet_pton(socket.AF_INET, addr)
94        return True
95    except socket.error:
96        return False
97
98def is_valid_mac (mac):
99    return bool(re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()))
100
101