示例#1
0
文件: escape.py 项目: walexzzy/escape
def clean():
    # Tailor Python path for importing mics functions without initialize
    # escape or util packages.
    import sys
    # Reset SIGTERM signal handler
    signal.signal(signal.SIGTERM, signal.SIG_DFL)
    # Import misc directly from util/ to avoid standard ESCAPE init steps
    sys.path.insert(0, PROJECT_ROOT + "/mininet")
    sys.path.insert(0, PROJECT_ROOT + "/escape/escape/util")
    if os.geteuid() != 0:
        print "Cleanup process requires root privilege!"
        return
    else:
        print "Run full cleaning process..."
        # Kill stacked ESCAPE processes
        from misc import run_cmd
        from misc import remove_junks_at_shutdown, remove_junks_at_boot
        # Remove remained temporarily files
        remove_junks_at_shutdown()
        # Remove log files from /tmp
        remove_junks_at_boot()
        esc_proc_filter = 'pgrep -af "%s"' % os.path.basename(__file__)
        for match in run_cmd(esc_proc_filter).splitlines():
            pid, pname = match.split(' ', 1)
            if "pgrep -af" in pname:
                continue
            if str(pid) != str(os.getpid()):
                print "Kill stucked ESCAPE process: %s" % match
                run_cmd("sudo -S kill %s" % pid)
        print "Cleaned."
        return
示例#2
0
def ips():
    '''Gets configured ips and interfaces

    Args:
        None

    Returns:
        ip_addrs (dict): output if success, err if failed
            dict is in format {ip/prefix: iface}

    '''
    try:
        ifcs = ifaces()
        ip_addrs = {}
        ip_addr = misc.run_cmd("ip addr")[1]
        lines = ip_addr.split("\n")
        for line in lines:
            if "inet" in line:
                cidr = line.split()[1]
                iface = line.split()[-1]
                for ifc in ifcs:
                    if iface == ifc['name']:
                        ip_addrs.update({cidr: iface})
        return ip_addrs
    except Exception as e:
        return e
示例#3
0
def ifaces():
    '''Gets all interfaces

    Args:
        None

    Returns:
        ifaces (list of dicts): output if success, err if failed
            dict is in format {name: X, flags: X, mtu: X, state: X, mac: X}

    '''
    try:
        ifaces = []
        ip_addr = misc.run_cmd("ip addr")[1]
        lines = ip_addr.split("\n")
        for line in lines:
            if "mtu" in line:
                iface = ['name', line.split(":")[1:2][0].strip()]
                flags = ['flags', line.split()[2]]
                mtu = line.split()[3:5]
                state = line.split()[7:9]
                ifc = iface + flags + mtu + state
                entry = {ifc[i]: ifc[i + 1] for i in range(0, len(ifc), 2)}
            if "ether" in line:
                mac = line.split()[1]
                entry.update({'mac': mac})
                ifaces.append(entry)
        return ifaces
    except Exception as e:
        return e
示例#4
0
def current_user():
    '''Gets the currently logged on user

    Args:
        None.

    Returns:
        currently logged-on user as string

    '''
    cmd = 'whoami'
    status, output, err = misc.run_cmd(cmd)
    if status != 0:
        response = err
    else:
        response = output.rstrip()
    return response
示例#5
0
def ping_host(host, count=1, timeout=1):
    '''Wrapper for ping using run_cmd()

    Args:
        host (str): hostname or IP
        count (int): number of times to ping (default 1)
        timeout (int): time to wait for response (default 1)

    Returns:
        response (str): output if success, err if failed

    '''
    cmd = "ping -c " + str(count) + " -W " + str(timeout) + " " + host
    status, output, err = misc.run_cmd(cmd)
    if status != 0:
        response = err
    else:
        response = output
    return response
示例#6
0
def routes():
    '''Gets configured routes

    Args:
        None

    Returns:
        entries (list of tuples): output if success, err if failed

    '''
    try:
        entries = []
        out = misc.run_cmd("netstat -rn")
        for line in out[1].rstrip().split("\n"):
            entries.append(tuple(line.split()))
        del entries[0]
        del entries[0]
        return entries
    except Exception as e:
        return e
示例#7
0
def users():
    '''Gets all logged on users

    Args:
        None.

    Returns:
        list of logged-on users as tuples

    '''
    cmd = 'who'
    status, output, err = misc.run_cmd(cmd)
    if status != 0:
        response = err
    else:
        response = []
        out = output.split("\n")
        if out[-1] == "":
            del out[-1]
        for line in out:
            response.append(tuple(line.rstrip().split()))
    return response
示例#8
0
def processes():
    '''Gets all running processes

    Args:
        None.

    Returns:
        list of processes as tuples

    '''
    cmd = 'ps -auwx'
    status, output, err = misc.run_cmd(cmd)
    if status != 0:
        response = err
    else:
        response = []
        out = output.split("\n")
        del out[0]
        if out[-1] == "":
            del out[-1]
        for line in out:
            response.append(tuple(line.rstrip().split()))
    return response
示例#9
0
import threading
import re

backupfile_regex = re.compile(r".*\d+\.torta")

debug = True
# debug = False

number_of_threads = 20
if debug:
    number_of_threads = 1

time.sleep(3)
dtrace_pid = int(
    run_cmd(
        'ps -e | awk \'$6 == "file_watcher/filetracer.dtrace" { print $1}\'')
    [0])
tracer_pid = os.getpid()

fd_dict = {}
process_itr = ProcessItr()
stop = False
session_id = sys.argv[1]


class SyncUnbuffered(object):
    def __init__(self, stream):
        self.stream = stream
        self.lock = threading.RLock()

    def write(self, data):