How to use _match_auto method in ATX

Best Python code snippet using ATX

mixin.py

Source:mixin.py Github

copy

Full Screen

...178 def bounds(self):179 if self._bounds is None:180 return None181 return self._bounds * self._cal_scale()182 def _match_auto(self, screen, search_img, threshold):183 """Maybe not a good idea184 """185 # 1. try template first186 ret = ac.find_template(screen, search_img)187 print "template/conficence:",ret188 if ret and ret['confidence'] > threshold:189 return FindPoint(ret['result'], ret['confidence'], 'template', matched=True)190 # 2. try sift191 ret = ac.find_sift(screen, search_img, min_match_count=10)192 print "sift/conficence:", ret193 if ret is None:194 return None195 matches, total = ret['confidence']196 print "other/conficence:", matches,total197 if 1.0 * matches / total > 0.5: # FIXME(ssx): sift just write here198 return FindPoint(ret['result'], ret['confidence'], 'sift', matched=True)199 return None200 def match_all(self, pattern):201 """202 Test method, not suggested to use203 """204 pattern = self.pattern_open(pattern)205 search_img = pattern.image206 screen = self.region_screenshot()207 screen = imutils.from_pillow(screen)208 points = ac.find_all_template(screen, search_img, maxcnt=10)209 return points210 def match(self, pattern, screen=None, rect=None, offset=None, threshold=None, method=None):211 """Check if image position in screen212 Args:213 - pattern: Image file name or opencv image object214 - screen (PIL.Image): optional, if not None, screenshot method will be called215 - threshold (float): it depends on the image match method216 - method (string): choices on <template | sift>217 Returns:218 None or FindPoint, For example:219 FindPoint(pos=(20, 30), method='tmpl', confidence=0.801, matched=True)220 Only when confidence > self.image_match_threshold, matched will be True221 Raises:222 TypeError: when image_match_method is invalid223 """224 pattern = self.pattern_open(pattern)225 search_img = pattern.image226 pattern_scale = self._cal_scale(pattern)227 if pattern_scale != 1.0:228 search_img = cv2.resize(search_img, (0, 0),229 fx=pattern_scale, fy=pattern_scale,230 interpolation=cv2.INTER_CUBIC)231 screen = screen or self.region_screenshot()232 threshold = threshold or pattern.threshold or self.image_match_threshold233 # handle offset if percent, ex (0.2, 0.8)234 dx, dy = offset or pattern.offset or (0, 0)235 dx = pattern.image.shape[1] * dx # opencv object width236 dy = pattern.image.shape[0] * dy # opencv object height237 dx, dy = int(dx * pattern_scale), int(dy * pattern_scale)238 # image match239 screen = imutils.from_pillow(screen) # convert to opencv image240 if rect and isinstance(rect, tuple) and len(rect) == 4:241 (x0, y0, x1, y1) = [v * pattern_scale for v in rect]242 (dx, dy) = dx + x0, dy + y0243 screen = imutils.crop(screen, x0, y0, x1, y1)244 # cv2.imwrite('cc.png', screen)245 match_method = method or self.image_match_method246 ret = None247 confidence = None248 matched = False249 match_method = "sift"250 print "threadhold:",threshold251 position = None252 print "compare method:",match_method253 if match_method == 'template': # IMG_METHOD_TMPL254 ret = ac.find_template(screen, search_img)255 if ret is None:256 return None257 confidence = ret['confidence']258 print confidence259 if confidence > threshold:260 matched = True261 (x, y) = ret['result']262 position = (x + dx, y + dy) # fix by offset263 elif match_method == 'sift':264 ret = ac.find_sift(screen, search_img, min_match_count=10)265 if ret is None:266 return None267 confidence = ret['confidence']268 matches, total = confidence269 if 1.0 * matches / total > 0.5: # FIXME(ssx): sift just write here270 matched = True271 (x, y) = ret['result']272 position = (x + dx, y + dy) # fix by offset273 elif match_method == 'auto':274 fp = self._match_auto(screen, search_img, threshold)275 if fp is None:276 return None277 (x, y) = fp.pos278 position = (x + dx, y + dy)279 return FindPoint(position, fp.confidence, fp.method, fp.matched)280 else:281 raise TypeError("Invalid image match method: %s" % (match_method,))282 (x, y) = ret['result']283 position = (x + dx, y + dy) # fix by offset284 if self.bounds:285 x, y = position286 position = (x + self.bounds.left, y + self.bounds.top)287 return FindPoint(position, confidence, match_method, matched=matched)288 def region(self, bounds):...

Full Screen

Full Screen

models.py

Source:models.py Github

copy

Full Screen

1from solarsan import logging2logger = logging.getLogger(__name__)3#from solarsan.models import CreatedModifiedDocMixIn4from solarsan.models import ReprMixIn5from solarsan.utils.network import cidr_to_netmask, netmask_to_cidr, is_cidr, is_netmask, is_ip, is_ip_in_network, is_domain6#from solarsan.template import quick_template7#import mongoengine as m8from augeas import Augeas9from solarsan.ha.arp import send_arp as garp10import ipcalc11#import IPy12import netifaces13import pynetlinux14import os15#import weakref16import sh17"""18Network19"""20def get_iface(name):21 return pynetlinux.ifconfig.Interface(name)22def get_ifup_ifaces():23 with open('/run/network/ifstate', 'rb') as f:24 for line in f.readlines():25 line = line.rstrip('\n')26 if not line:27 continue28 yield line.split('=', 1)[0]29def get_configured_ifaces():30 aug = Augeas(flags=Augeas.NO_MODL_AUTOLOAD)31 aug.add_transform('interfaces', '/etc/network/interfaces')32 aug.load()33 base = '/files/etc/network/interfaces'34 for m in aug.match('%s/iface' % base):35 yield aug.get(m)36 aug.close()37def is_iface_ifup(name):38 match_name = '%s=%s' % (name, name)39 with open('/run/network/ifstate', 'rb') as f:40 for line in f.readlines():41 line = line.rstrip('\n')42 if line == match_name:43 return True44 return False45class AugeasWrap(object):46 _transform = 'interfaces'47 _file = None48 _attrs = []49 _map = {}50 _match = None51 __aug = None52 @property53 def _aug(self):54 if not self.__aug:55 self.__aug = Augeas(flags=Augeas.NO_MODL_AUTOLOAD)56 self.__aug.add_transform(self._transform, self._file)57 self.__aug.load()58 return self.__aug59 _debug = False60 def exists(self):61 return bool(self.get())62 def _abspath(self, path):63 if not path or not (path.startswith('/augeas') or path.startswith('/files') or path.startswith('$')):64 path = '%s%s' % (self._match, path or '')65 return path or ''66 def get(self, path=None):67 ret = self._aug.get(self._abspath(path))68 if self._debug:69 logger.debug('get path=%s value=%s', self._abspath(path), ret)70 return ret71 def set(self, value, path=None):72 value = str(value)73 if self._debug:74 logger.debug('set path=%s value=%s', self._abspath(path), value)75 return self._aug.set(self._abspath(path), value)76 def match(self, path=None):77 if self._debug:78 logger.debug('match path=%s', self._abspath(path))79 return self._aug.match(self._abspath(path))80 def remove(self, path=None):81 if self._debug:82 logger.debug('remove path=%s', self._abspath(path))83 return self._aug.remove(self._abspath(path))84 def insert(self, value, path=None, before=True):85 value = str(value)86 if self._debug:87 logger.debug('insert path=%s value=%s', self._abspath(path), value)88 return self._aug.insert(self._abspath(path), value, before=before)89 def _print(self, path=None):90 path = self._abspath(path)91 get = self.get(path)92 logger.info("[%s] = '%s'", path, get)93 try:94 for match in self.match('%s//*' % path):95 logger.info("[%s] = '%s'", match, self._aug.get(match))96 except RuntimeError:97 pass98 def _all_attrs(self):99 return self._attrs + self._map.keys()100class DebianInterfaceConfig(ReprMixIn, AugeasWrap):101 _transform = 'interfaces'102 _file = '/etc/network/interfaces'103 _match_auto = None104 _attrs = ['family', 'method', 'address', 'netmask', 'gateway', 'mtu']105 _map = {'dns-nameservers': 'nameservers',106 'dns-search': 'search'}107 name = None108 def quick_setup(self, family='inet', method='static', netmask='255.255.255.0', **kwargs):109 if family:110 self.family = family111 if method:112 self.method = method113 if method in ['static'] and netmask:114 self.netmask = netmask115 if kwargs:116 for k, v in kwargs.iteritems():117 setattr(self, k, v)118 @property119 def auto(self):120 return bool(self.get('$ifaces/auto/*[. = "%s"]' % str(self.name)))121 @auto.setter122 def auto(self, value):123 value = bool(value)124 if value is True and not self.auto:125 self.set(str(self.name), '$ifaces/auto[last()+1]/1')126 elif value is False and self.auto:127 self.remove('$ifaces/auto/*[. = "%s"]' % str(self.name))128 @property129 def family(self):130 return self.get('%s/family' % self._match)131 @family.setter132 def family(self, value):133 if not value in ['inet']:134 raise ValueError('%s is not a valid family')135 return self.set(value, '%s/family' % self._match)136 @property137 def method(self):138 return self.get('%s/method' % self._match)139 @method.setter140 def method(self, value):141 if not value in ['dhcp', 'static', 'manual']:142 raise ValueError('%s is not a valid method' % value)143 return self.set(value, '%s/method' % self._match)144 proto = method145 @property146 def ip(self):147 return self.get('%s/address' % self._match)148 @ip.setter149 def ip(self, value):150 if not is_ip(value):151 raise ValueError('%s is not a valid ipaddr' % value)152 return self.set(value, '%s/address' % self._match)153 ipaddr = ip154 @property155 def address(self):156 if self.ip is None and self.cidr is None:157 return None158 return '%s/%s' % (self.ipaddr, self.cidr)159 @address.setter160 def address(self, value):161 if not self.family:162 self.family = 'inet'163 ip = None164 mask = None165 if '/' in value:166 ip, mask = value.split('/', 1)167 else:168 ip = value169 if not self.method:170 if ip or mask:171 self.method = 'static'172 else:173 self.method = 'manual'174 if ip:175 self.ip = ip176 if mask:177 if is_netmask(mask):178 self.netmask = mask179 elif is_cidr(mask):180 self.cidr = mask181 else:182 raise ValueError('%s is not a valid netmask or cidr' % mask)183 @property184 def netmask(self):185 return self.get('%s/netmask' % self._match)186 @netmask.setter187 def netmask(self, value):188 if not is_netmask(value):189 raise ValueError('%s is not a valid netmask' % value)190 return self.set(value, '%s/netmask' % self._match)191 @property192 def cidr(self):193 netmask = self.netmask194 if not netmask:195 return196 return netmask_to_cidr(netmask)197 @cidr.setter198 def cidr(self, value):199 if not is_cidr(value):200 raise ValueError('%s is not a valid cidr' % value)201 self.netmask = cidr_to_netmask(value)202 @property203 def gateway(self):204 return self.get('%s/gateway' % self._match)205 @gateway.setter206 def gateway(self, value):207 if not is_ip(value):208 raise ValueError('%s is not a valid gateway' % value)209 return self.set(value, '%s/gateway' % self._match)210 @property211 def nameservers(self):212 return self.get('%s/nameservers' % self._match)213 @nameservers.setter214 def nameservers(self, value):215 value = value.split()216 for ns in value:217 if not is_ip(ns):218 raise ValueError('%s is not a valid nameserver' % ns)219 value = ' '.join(value)220 return self.set(value, '%s/nameservers' % self._match)221 @property222 def search(self):223 return self.get('%s/search' % self._match)224 @search.setter225 def search(self, value):226 value = value.split()227 for domain in value:228 if not is_domain(domain):229 raise ValueError('%s is not a valid search domain' % domain)230 value = ' '.join(value)231 return self.set(value, '%s/search' % self._match)232 @property233 def mtu(self):234 mtu = self.get('%s/mtu' % self._match)235 if mtu:236 return int(mtu)237 @mtu.setter238 def mtu(self, value):239 value = int(value)240 return self.set(value, '%s/mtu' % self._match)241 def __init__(self, name_or_nic, replace=False):242 if isinstance(name_or_nic, Nic):243 nic = name_or_nic244 else:245 nic = Nic(name_or_nic)246 self.name = str(nic.name)247 super(DebianInterfaceConfig, self).__init__()248 self.load()249 if replace and self._exists:250 logger.warning('Replacing existing interface config %s due to replace=%s', self, replace)251 logger.warning('Removed %s entires', self.remove())252 def exists_auto(self):253 return bool(self.get(self._match_auto))254 def load(self):255 self._aug.defvar('ifaces', '/files%s' % self._file)256 self._top_node = '$ifaces'257 self._match = '$ifaces/iface[. = "%s"]' % self.name258 self._match_auto = '$ifaces/auto/[* = "%s"]' % self.name259 self._exists = self.exists()260 if not self._exists:261 self.set(self.name, None)262 #def set(self, value, path=None):263 # if not self._exists:264 # super(DebianInterfaceConfig, self).set(self.name)265 # return super(DebianInterfaceConfig, self).set(value, path=path)266 def update(self, **kwargs):267 if not kwargs:268 return269 all_attrs = self._all_attrs()270 for k, v in kwargs.iteritems():271 if k in all_attrs:272 setattr(self, k, v)273 def save(self, apply=False):274 if self.gateway and not is_ip_in_network(self.address, self.gateway):275 raise ValueError('Gateway %s is not valid (not in %s)' % (self.gateway, self.address))276 if apply:277 self.ifdown()278 ret = self._aug.save()279 self._exists = self.exists()280 if apply and ret:281 self.ifup()282 return ret283 @property284 def type(self):285 if self.name.startswith('eth'):286 return 'ethernet'287 elif self.name.startswith('ib'):288 return 'infiniband'289 elif self.name.startswith('lo'):290 return 'local'291 def ifdown(self, reset=False):292 logger.info('Bringing down interface %s', self.name)293 ret = True294 try:295 sh.ifdown(self.name)296 except:297 logger.warning('Error Bringing down interface %s', self.name)298 ret = False299 if reset:300 logger.warning('Resetting interface %s', self.name)301 for i in ['0.0.0.0/0', 'down']:302 try:303 sh.ifconfig(self.name, i)304 except:305 pass306 return ret307 def ifup(self, send_arp=True):308 logger.info('Bringing up interface %s', self.name)309 try:310 sh.ifup(self.name)311 if send_arp:312 garp(self.name, self.ip)313 return True314 except:315 logger.error('Error Bringing up interface %s', self.name)316 return False317 def is_ifup(self):318 return is_iface_ifup(self.name)319class Nic(ReprMixIn):320 name = None321 def __init__(self, name):322 self.name = name323 # This has to be a basestring324 self._obj = get_iface(str(name))325 _config = None326 @property327 def config(self):328 if not self._config:329 self._config = DebianInterfaceConfig(self)330 return self._config331 #config = None332 #if hasattr(self, '_config'):333 # config = self._config()334 #if config is None:335 # #self._config, created = NicConfig.objects.get_or_create(name=self.name)336 # config = DebianInterfaceConfig(self)337 # self._config = weakref.ref(config)338 #return config339 def ifdown(self):340 return self.config.ifdown()341 def ifup(self, send_arp=None):342 return self.config.ifup(send_arp=send_arp)343 def is_ifup(self):344 return self.config.is_ifup()345 @property346 def broadcast(self):347 net = ipcalc.Network('%s/%s' % (self.ipaddr, self.cidr))348 return str(net.broadcast())349 @property350 def ipaddr(self):351 return self._obj.get_ip()352 @property353 def netmask(self):354 return cidr_to_netmask(self._obj.get_netmask())355 @property356 def cidr(self):357 return self._obj.get_netmask()358 @property359 def mac(self):360 return self._obj.get_mac()361 @property362 def mtu(self):363 fn = '/sys/class/net/%s/mtu' % self.name364 if not os.path.isfile(fn):365 return366 with open(fn) as f:367 return int(f.read())368 '''369 @property370 def addrs(self):371 ret = dict([(netifaces.address_families[x[0]], x[1])372 for x in netifaces.ifaddresses(self.name).items()373 ])374 if 'AF_INET6' in ret:375 ## TODO Fix bug in the real issue here, netifaces, where it puts your damn iface name after your IPv6 addr376 inet6_addrs = []377 for addr in ret['AF_INET6']:378 if '%' in addr['addr']:379 addr['addr'] = addr['addr'][:addr['addr'].index('%')]380 inet6_addrs.append(addr)381 ret['AF_INET6'] = inet6_addrs382 return ret383 '''384 @property385 def addrs(self):386 return netifaces.ifaddresses(self.name)387 @property388 def type(self):389 if self.name.startswith('eth'):390 return 'ethernet'391 elif self.name.startswith('ib'):392 return 'infiniband'393 elif self.name.startswith('lo'):394 return 'local'395 #def get_absolute_url(self):396 # return reverse('network-interface-detail', kwargs={'slug': self.name})397 def __unicode__(self):398 if self.ipaddr and self.cidr:399 return '%s (%s/%s)' % (self.name, self.ipaddr, self.cidr)400 else:401 return self.name402 @classmethod403 def list(cls):404 ret = {}405 for x in netifaces.interfaces():406 try:407 ret[x] = Nic(x)408 except:409 pass410 #return dict([(x, lambda Nic(x) except: None) for x in netifaces.interfaces()])411 return ret412def get_all_local_ipv4_addrs(nics=None, lo=False):413 if nics is None:414 nics = netifaces.interfaces()415 ret = {}416 for name in nics:417 if not lo and name == 'lo':418 continue419 try:420 addrs = netifaces.ifaddresses(name)[netifaces.AF_INET]421 except KeyError:422 addrs = []423 ret[name] = addrs...

Full Screen

Full Screen

config.py

Source:config.py Github

copy

Full Screen

1""" Debian networking management. """2import logging3log = logging.getLogger(__name__)4from ..utils.reprs import ReprMixIn5from ..utils.network import cidr_to_netmask, netmask_to_cidr, is_cidr, is_netmask, is_ip, is_ip_in_network, is_domain6from ..utils import arp7from augeas import Augeas8import ipcalc9import netifaces10import pynetlinux11import os12import sh13def get_iface(name):14 return pynetlinux.ifconfig.Interface(name)15def list_ifaces():16 for x in netifaces.interfaces():17 yield x18def list_ifup_ifaces():19 with open('/run/network/ifstate', 'rb') as f:20 for line in f.readlines():21 line = line.rstrip('\n')22 if line:23 yield line.split('=', 1)[0]24def list_configured_ifaces():25 aug = Augeas(flags=Augeas.NO_MODL_AUTOLOAD)26 aug.add_transform('interfaces', '/etc/network/interfaces')27 aug.load()28 base = '/files/etc/network/interfaces'29 for m in aug.match('%s/iface' % base):30 yield aug.get(m)31 aug.close()32def is_iface_ifup(name):33 for iface in list_ifup_ifaces():34 if iface == name:35 return True36 return False37class AugeasWrap(object):38 _transform = 'interfaces'39 _file = None40 _attrs = []41 _map = {}42 _match = None43 __aug = None44 @property45 def _aug(self):46 if not self.__aug:47 self.__aug = Augeas(flags=Augeas.NO_MODL_AUTOLOAD)48 self.__aug.add_transform(self._transform, self._file)49 self.__aug.load()50 return self.__aug51 _debug = False52 def exists(self):53 return bool(self.get())54 def _abspath(self, path):55 if not path or not (path.startswith('/augeas') or path.startswith('/files') or path.startswith('$')):56 path = '%s%s' % (self._match, path or '')57 return path or ''58 def get(self, path=None):59 ret = self._aug.get(self._abspath(path))60 if self._debug:61 log.debug('get path=%s value=%s', self._abspath(path), ret)62 return ret63 def set(self, value, path=None):64 value = str(value)65 if self._debug:66 log.debug('set path=%s value=%s', self._abspath(path), value)67 return self._aug.set(self._abspath(path), value)68 def match(self, path=None):69 if self._debug:70 log.debug('match path=%s', self._abspath(path))71 return self._aug.match(self._abspath(path))72 def remove(self, path=None):73 if self._debug:74 log.debug('remove path=%s', self._abspath(path))75 return self._aug.remove(self._abspath(path))76 def insert(self, value, path=None, before=True):77 value = str(value)78 if self._debug:79 log.debug('insert path=%s value=%s', self._abspath(path), value)80 return self._aug.insert(self._abspath(path), value, before=before)81 def _print(self, path=None):82 path = self._abspath(path)83 get = self.get(path)84 log.info("[%s] = '%s'", path, get)85 try:86 for match in self.match('%s//*' % path):87 log.info("[%s] = '%s'", match, self._aug.get(match))88 except RuntimeError:89 pass90 def _all_attrs(self):91 return self._attrs + self._map.keys()92class DebianInterfaceConfig(ReprMixIn, AugeasWrap):93 _transform = 'interfaces'94 _file = '/etc/network/interfaces'95 _match_auto = None96 _attrs = ['family', 'method', 'address', 'netmask', 'gateway', 'mtu']97 _map = {'dns-nameservers': 'nameservers',98 'dns-search': 'search'}99 name = None100 def quick_setup(self, family='inet', method='static', netmask='255.255.255.0', **kwargs):101 if family:102 self.family = family103 if method:104 self.method = method105 if method in ['static'] and netmask:106 self.netmask = netmask107 if kwargs:108 for k, v in kwargs.iteritems():109 setattr(self, k, v)110 @property111 def auto(self):112 return bool(self.get('$ifaces/auto/*[. = "%s"]' % str(self.name)))113 @auto.setter114 def auto(self, value):115 value = bool(value)116 if value is True and not self.auto:117 self.set(str(self.name), '$ifaces/auto[last()+1]/1')118 elif value is False and self.auto:119 self.remove('$ifaces/auto/*[. = "%s"]' % str(self.name))120 @property121 def family(self):122 return self.get('%s/family' % self._match)123 @family.setter124 def family(self, value):125 if not value in ['inet']:126 raise ValueError('%s is not a valid family')127 return self.set(value, '%s/family' % self._match)128 @property129 def method(self):130 return self.get('%s/method' % self._match)131 @method.setter132 def method(self, value):133 if not value in ['dhcp', 'static', 'manual']:134 raise ValueError('%s is not a valid method' % value)135 return self.set(value, '%s/method' % self._match)136 proto = method137 @property138 def ip(self):139 return self.get('%s/address' % self._match)140 @ip.setter141 def ip(self, value):142 if not is_ip(value):143 raise ValueError('%s is not a valid ipaddr' % value)144 return self.set(value, '%s/address' % self._match)145 ipaddr = ip146 @property147 def address(self):148 if self.ip is None and self.cidr is None:149 return None150 return '%s/%s' % (self.ipaddr, self.cidr)151 @address.setter152 def address(self, value):153 if not self.family:154 self.family = 'inet'155 ip = None156 mask = None157 if '/' in value:158 ip, mask = value.split('/', 1)159 else:160 ip = value161 if not self.method:162 if ip or mask:163 self.method = 'static'164 else:165 self.method = 'manual'166 if ip:167 self.ip = ip168 if mask:169 if is_netmask(mask):170 self.netmask = mask171 elif is_cidr(mask):172 self.cidr = mask173 else:174 raise ValueError('%s is not a valid netmask or cidr' % mask)175 @property176 def netmask(self):177 return self.get('%s/netmask' % self._match)178 @netmask.setter179 def netmask(self, value):180 if not is_netmask(value):181 raise ValueError('%s is not a valid netmask' % value)182 return self.set(value, '%s/netmask' % self._match)183 @property184 def cidr(self):185 netmask = self.netmask186 if not netmask:187 return188 return netmask_to_cidr(netmask)189 @cidr.setter190 def cidr(self, value):191 if not is_cidr(value):192 raise ValueError('%s is not a valid cidr' % value)193 self.netmask = cidr_to_netmask(value)194 @property195 def gateway(self):196 return self.get('%s/gateway' % self._match)197 @gateway.setter198 def gateway(self, value):199 if not is_ip(value):200 raise ValueError('%s is not a valid gateway' % value)201 return self.set(value, '%s/gateway' % self._match)202 @property203 def nameservers(self):204 return self.get('%s/nameservers' % self._match)205 @nameservers.setter206 def nameservers(self, value):207 value = value.split()208 for ns in value:209 if not is_ip(ns):210 raise ValueError('%s is not a valid nameserver' % ns)211 value = ' '.join(value)212 return self.set(value, '%s/nameservers' % self._match)213 @property214 def search(self):215 return self.get('%s/search' % self._match)216 @search.setter217 def search(self, value):218 value = value.split()219 for domain in value:220 if not is_domain(domain):221 raise ValueError('%s is not a valid search domain' % domain)222 value = ' '.join(value)223 return self.set(value, '%s/search' % self._match)224 @property225 def mtu(self):226 mtu = self.get('%s/mtu' % self._match)227 if mtu:228 return int(mtu)229 @mtu.setter230 def mtu(self, value):231 value = int(value)232 return self.set(value, '%s/mtu' % self._match)233 def __init__(self, name_or_nic, replace=False):234 if isinstance(name_or_nic, Nic):235 nic = name_or_nic236 else:237 nic = Nic(name_or_nic)238 self.name = str(nic.name)239 super(DebianInterfaceConfig, self).__init__()240 self.load()241 if replace and self._exists:242 log.warning('Replacing existing interface config %s due to replace=%s', self, replace)243 log.warning('Removed %s entires', self.remove())244 def exists_auto(self):245 return bool(self.get(self._match_auto))246 def load(self):247 self._aug.defvar('ifaces', '/files%s' % self._file)248 self._top_node = '$ifaces'249 self._match = '$ifaces/iface[. = "%s"]' % self.name250 self._match_auto = '$ifaces/auto/[* = "%s"]' % self.name251 self._exists = self.exists()252 if not self._exists:253 self.set(self.name, None)254 #def set(self, value, path=None):255 # if not self._exists:256 # super(DebianInterfaceConfig, self).set(self.name)257 # return super(DebianInterfaceConfig, self).set(value, path=path)258 def update(self, **kwargs):259 if not kwargs:260 return261 all_attrs = self._all_attrs()262 for k, v in kwargs.iteritems():263 if k in all_attrs:264 setattr(self, k, v)265 def save(self, apply=False):266 if self.gateway and not is_ip_in_network(self.address, self.gateway):267 raise ValueError('Gateway %s is not valid (not in %s)' % (self.gateway, self.address))268 if apply:269 self.ifdown()270 ret = self._aug.save()271 self._exists = self.exists()272 if apply and ret:273 self.ifup()274 return ret275 @property276 def type(self):277 if self.name.startswith('eth'):278 return 'ethernet'279 elif self.name.startswith('ib'):280 return 'infiniband'281 elif self.name.startswith('lo'):282 return 'local'283 def ifdown(self, reset=False):284 log.info('Bringing down interface %s', self.name)285 ret = True286 try:287 sh.ifdown(self.name)288 except:289 log.warning('Error Bringing down interface %s', self.name)290 ret = False291 if reset:292 log.warning('Resetting interface %s', self.name)293 for i in ['0.0.0.0/0', 'down']:294 try:295 sh.ifconfig(self.name, i)296 except:297 pass298 return ret299 def ifup(self, send_arp=True):300 log.info('Bringing up interface %s', self.name)301 try:302 sh.ifup(self.name)303 if send_arp:304 arp.send_arp(self.name, self.ip)305 return True306 except:307 log.error('Error Bringing up interface %s', self.name)308 return False309 def is_ifup(self):310 return is_iface_ifup(self.name)311class Nic(ReprMixIn):312 name = None313 def __init__(self, name):314 self.name = name315 # This has to be a basestring316 self._obj = get_iface(str(name))317 _config = None318 @property319 def config(self):320 if not self._config:321 self._config = DebianInterfaceConfig(self)322 return self._config323 #config = None324 #if hasattr(self, '_config'):325 # config = self._config()326 #if config is None:327 # #self._config, created = NicConfig.objects.get_or_create(name=self.name)328 # config = DebianInterfaceConfig(self)329 # self._config = weakref.ref(config)330 #return config331 def ifdown(self):332 return self.config.ifdown()333 def ifup(self, send_arp=None):334 return self.config.ifup(send_arp=send_arp)335 def is_ifup(self):336 return self.config.is_ifup()337 @property338 def broadcast(self):339 net = ipcalc.Network('%s/%s' % (self.ipaddr, self.cidr))340 return str(net.broadcast())341 @property342 def ipaddr(self):343 return self._obj.get_ip()344 @property345 def netmask(self):346 return cidr_to_netmask(self._obj.get_netmask())347 @property348 def cidr(self):349 return self._obj.get_netmask()350 @property351 def mac(self):352 return self._obj.get_mac()353 @property354 def mtu(self):355 fn = '/sys/class/net/%s/mtu' % self.name356 if not os.path.isfile(fn):357 return358 with open(fn) as f:359 return int(f.read())360 '''361 @property362 def addrs(self):363 ret = dict([(netifaces.address_families[x[0]], x[1])364 for x in netifaces.ifaddresses(self.name).items()365 ])366 if 'AF_INET6' in ret:367 ## TODO Fix bug in the real issue here, netifaces, where it puts your damn iface name after your IPv6 addr368 inet6_addrs = []369 for addr in ret['AF_INET6']:370 if '%' in addr['addr']:371 addr['addr'] = addr['addr'][:addr['addr'].index('%')]372 inet6_addrs.append(addr)373 ret['AF_INET6'] = inet6_addrs374 return ret375 '''376 @property377 def addrs(self):378 return netifaces.ifaddresses(self.name)379 @property380 def type(self):381 if self.name.startswith('eth'):382 return 'ethernet'383 elif self.name.startswith('ib'):384 return 'infiniband'385 elif self.name.startswith('lo'):386 return 'local'387 #def get_absolute_url(self):388 # return reverse('network-interface-detail', kwargs={'slug': self.name})389 def __unicode__(self):390 if self.ipaddr and self.cidr:391 return '%s (%s/%s)' % (self.name, self.ipaddr, self.cidr)392 else:393 return self.name394 @classmethod395 def list(cls):396 for x in netifaces.interfaces():397 yield Nic(x)398def get_all_local_ipv4_addrs(nics=None, lo=False):399 if nics is None:400 nics = netifaces.interfaces()401 ret = {}402 for name in nics:403 if not lo and name == 'lo':404 continue405 try:406 addrs = netifaces.ifaddresses(name)[netifaces.AF_INET]407 except KeyError:408 addrs = []409 ret[name] = addrs...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ATX automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful