Exemplo n.º 1
0
    def __init__(self, brint_name=BRINT_NAME, capsulator_bin=CAPSULATOR_BIN):
        """Performs checks to validate setting up a capsulator tunnel.

        :param str brint_name:
        :param str capsulator_bin:
        :raises: NoBridgeFoundException, NoCapsulatorBinException

        """
        # print "Constructing CapsulatorAgent %s" % repr(self)
        try:
            subprocess.check_call(["ifconfig", brint_name, "up"], 
                                  stdout=open("/dev/null", "w"))
        except subprocess.CalledProcessError:
            # bridge does not exist
            raise NoBridgeFoundException()
        else:
            if ifconfig.ifconfig(brint_name)["addr"] == "0.0.0.0":
                print "Setting %s ip to %s" % (brint_name, BRIDGE_IP)
                subprocess.check_call(
                    [
                        "ifconfig", 
                        brint_name, 
                        BRIDGE_IP
                    ], 
                    stdout=open("/dev/null", "w")
                )

        self.brint_name = brint_name
        try:
            subprocess.check_call([capsulator_bin],
                                  stdout=open("/dev/null", "w"))
        except subprocess.CalledProcessError:
            # capsulator not installed
            raise NoCapsulatorBinException()
        self.capsulator_bin = capsulator_bin
Exemplo n.º 2
0
    def _get_own_ip_addr(self, interface):
        try:
            ifconf = ifconfig.ifconfig(interface)
            return ifconf.get('addr')
        except Exception as e:
            print "Error getting own IP address: %s" % e.message

        # TODO(mike) get ip address of access point and assign it to
        # forward_to in config
        # ipsubprocess.check_output([ifconfig])
Exemplo n.º 3
0
    def create(self, config):
        """Sets up a capsulator tunnel using the information in config.
        A typical configuration looks like this::

            {  
                "attach_to": "eth0",
                "forward_to": "10.5.8.202",
                "command": "create",
                "name": "tun0",
                "tunnel_tag": "1"
            }

        :param dict config:
        :raises: InvalidConfigurationException, 
                 InterfaceNameAlreadyInUseException,
                 CannotBringInterfaceUpException,
                 CannotAddInterfaceToBridgeException

        """
        print "Creating %s" % config["name"]
        try:
            attach_to = config["attach_to"]
            forward_to = config["forward_to"]
            name = config["name"]
            tunnel_tag = config["tunnel_tag"]
        except Exception as e:
            raise InvalidConfigurationException()
        if (name in CapsulatorAgent.processes or 
            ifconfig.ifconfig(name).get("brdaddr") != "0.0.0.0"):
            raise InterfaceNameAlreadyInUseException(name=name)

        command = [self.capsulator_bin,"-t", attach_to, "-f", forward_to, 
                   "-vb", name + "#" + tunnel_tag]
        pid = subprocess.Popen(command)
        CapsulatorAgent.processes[name] = [pid]
        time.sleep(1)
        try:
            subprocess.check_call(["ifconfig", name, "up"])
        except subprocess.CalledProcessError:
            CapsulatorAgent.stop(name)
            raise CannotBringInterfaceUpException(name=name)
        try:
            subprocess.check_call(["brctl", "addif", self.brint_name, name])
        except subprocess.CalledProcessError:
            CapsulatorAgent.stop(name)
            raise CannotAddInterfaceToBridgeException(name=name,
                                                      bridge=self.brint_name)
Exemplo n.º 4
0
def network(request):
	from ifconfig import ifconfig
	import subprocess
	from django.core.validators import validate_ipv46_address, RegexValidator
	from django.core.exceptions import ValidationError
	from apc.forms import NetForm
	from apc.network import interfaces
	c={}
	eth0=ifconfig('eth0')
	cmd_route="/sbin/ip route | awk \'/default/{print $3}\'"
	p_route=subprocess.Popen(cmd_route,stdout=subprocess.PIPE,shell=True)
	(gateway,err)=p_route.communicate()
	cmd_hostname="/bin/hostname"
	p_hostname=subprocess.Popen(cmd_hostname,stdout=subprocess.PIPE,shell=True)
	(hostname,err)=p_hostname.communicate()
	cmd_speed="dmesg|grep -i eth0:\\ link\\ up|cut -d\',\' -f2"
	cmd_speed_mode="dmesg|grep -i eth0:\\ link\\ up|cut -d\',\' -f3"
	speed_proc=subprocess.Popen(cmd_speed,stdout=subprocess.PIPE,shell=True)
	(speed,err)=speed_proc.communicate()
	speed_mode_proc=subprocess.Popen(cmd_speed_mode,stdout=subprocess.PIPE,shell=True)
	(speed_mode,err)=speed_mode_proc.communicate()
	c['gateway']=gateway[:-1]
	c['hostname']=hostname[:-1]
	c['ip']=eth0['addr']
	c['mask']=eth0['netmask']
	cmd_bootmode='cat /etc/network/interfaces |grep ^iface\\ eth0 | awk -F \' \' \'{print $4}\''
	proc_bootmode=subprocess.Popen(cmd_bootmode,stdout=subprocess.PIPE,shell=True)
	(bootmod,err)=proc_bootmode.communicate()
	if bootmod[:-1]=='static':
		bootmode='1'
	else:
		bootmode='2'

	if request.method == 'POST':
		form = NetForm(request.POST)
		
		if form.is_valid():
			net_dict={}
			net_dict['ipaddress']=form.cleaned_data.get('ipaddress')
			net_dict['subnetmask']=form.cleaned_data.get('subnetmask')
			net_dict['bootmode']=form.cleaned_data.get('bootmode')
			net_dict['gateway']=form.cleaned_data.get('gateway')
			net_dict['hostname']=form.cleaned_data.get('hostname')
			if (c['ip']==net_dict['ipaddress']) and (c['mask']==net_dict['subnetmask']) and \
			(c['gateway']==net_dict['gateway']) and (c['hostname']==net_dict['hostname']) and \
			(bootmode==net_dict['bootmode']):
				return redirect('/network/')
			else:
				network=interfaces()
				network.write_template(net_dict['bootmode'],**net_dict)
				return HttpResponse("The system is rebooting now to effect the changes, Please wait...")
	else:
		
		
		default_data = {'bootmode':'2','ipaddress': eth0['addr'], 'subnetmask': eth0['netmask'],'gateway':gateway[:-1], 'hostname':hostname[:-1]}
		form=NetForm(default_data,auto_id=True)

	

	
		#form=NetForm(auto_id=False)
	c['form'] = form
	c['bootmode']=bootmod[:-1]
	c['hwaddr']=eth0['hwaddr']
	if speed and speed_mode:
		c['speed']=speed
		c['speed_mode']=speed_mode
	else:
		c['speed']='Could not retrieved.'
		c['speed_mode']='...check interface card'

	#ip link show eth0 | awk '/ether/ {print $2}'
	c.update(csrf(request))
	return render_to_response("network.html",c)
    while(True):
        idx = idx + 1
        net_before = psutil.network_io_counters(pernic=True)['eth0']
        disk_before = psutil.disk_io_counters()
        time.sleep(INTERVAL)
        net_after = psutil.network_io_counters(pernic=True)['eth0']
        disk_after = psutil.disk_io_counters()
        disk_usage = psutil.disk_usage('/').percent
        disk_free = psutil.disk_usage('/').free
        disk_read = (disk_after.read_bytes - disk_before.read_bytes)/INTERVAL
        disk_write = (disk_after.write_bytes - disk_before.write_bytes)/INTERVAL
        sent_bytes = (net_after.bytes_sent - net_before.bytes_sent)/INTERVAL
        recv_bytes = (net_after.bytes_recv - net_before.bytes_recv)/INTERVAL
        #TODO - Use load average instead of cpu_percent, it's too quick
        cpu = psutil.cpu_percent()
        ip = ifconfig('eth0')
        pt.produce('{"name":"Network","feed":{'+
                '"addr":"'+ip['addr']+
                '","hwaddr":"'+ip['hwaddr']+
                '","sentBps":'+str(sent_bytes)+
                ',"recvBps":'+str(recv_bytes)+'}}')
        pt.produce('{"name":"Disk","feed":{'+
                '"readBps":'+str(disk_read)+
                ',"writeBps":'+str(disk_write)+
                ',"free":'+str(disk_free)+
                ',"usage":'+str(disk_usage)+'}}')
        pt.produce('{"name":"CPU","feed":{'+
                '"utilization":'+str(cpu)+'}}')
        if idx%CAPABILITIES == 0:
            pt.produce('{"capabilities": {"feeds": ["Network","Disk","CPU","GPIO"]}}')
#TODO - Errors in the received data callback need exception handling too!
Exemplo n.º 6
0
        
        try:
            os.mkdir(datapath)
            os.chmod(datapath,stat.S_IRWXO | stat.S_IRWXG | stat.S_IRWXU)
        except:
            corelog.exception("Couldn't create data path %s" % datapath)
        for id,ibob in self.iBOBProxies.items():
            if id in ibobids:
                ibob.start_writing(os.path.join(datapath,'ibob%d.h5' % id))
        

if __name__=="__main__":
    import Pyro
    import ifconfig
    for k in range(4):
        cfg = ifconfig.ifconfig('eth%d'%k)
        if cfg['addr'].startswith('192.168'):
            myip = cfg['addr']
            break
    
    print "My IP is:",myip
    Pyro.config.PYRO_HOST = myip
    corelog.info("Starting iBOBProcessServer on %s" % myip)

    Pyro.core.initServer()
    Pyro.config.PYRO_MULTITHREADED = 0
    ns = Pyro.naming.NameServerLocator().getNS()
    try:
        ns.unregister('ProcessServer')
    except:
        pass
Exemplo n.º 7
0
 def __init__(self, interface = 'wlan0'):
     self.ifconfig_output = ifconfig(interface)
Exemplo n.º 8
0
	def GET(self):
		ifcon = ifconfig.ifconfig('eth0')
		m = re.match(r'\d+', ifcon['netmask'])
		flag = m.group()
		remote =  web.template.frender('templates/remote.html')
		return remote(ifcon,flag)
Exemplo n.º 9
0
                                    body=data_for_sender)

# Executed when run from the command line.
# *** NORMAL USAGE ***        
if __name__ == '__main__':

    ## Working directory for all files
    os.chdir('/usr/aurora')

    ######
    # Set the provision server IP/port here
    prov_server = 'http://10.5.8.3:5555/initial_ap_config_request/'
    #######

    # Get mac address
    mac = ifconfig("eth0")["hwaddr"]
    # Put in HTTP request to get config
    try:
        request = requests.get(prov_server + mac)
    except requests.exceptions.ConnectionError:
        print("Unable to connect to provision server @ " + prov_server)
        exit()

    config_full = request.json()
    queue = config_full['queue']
    if 'region' in config_full.keys():
        region = config_full['region']
    else:
        region = None
    config = {}
    config['default_config'] = config_full['default_config']