本文整理汇总了Python中uuid.get_mac函数的典型用法代码示例。如果您正苦于以下问题:Python get_mac函数的具体用法?Python get_mac怎么用?Python get_mac使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_mac函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self):
xbmc.log("Reading Settings.xml")
if int(xbmc.getInfoLabel('System.BuildVersion')[:2]) < 18:
XBMC_DIALOG_BUSY_OPEN = "ActivateWindow(busydialog)"
XBMC_DIALOG_BUSY_CLOSE = "Dialog.Close(busydialog)"
from uuid import getnode as get_mac
if hasattr(os, 'uname'):
system = os.uname()[4]
else:
import platform
system = platform.uname()[5]
if system == 'armv6l':
try:
mac = open('/sys/class/net/eth0/address').readline()
self.XNEWA_MAC = hex(int('0x'+ mac.replace(':',''),16))
except:
self.XNEWA_MAC = str(hex(get_mac()))
else:
self.XNEWA_MAC = str(hex(get_mac()))
self.loadFromSettingsXML()
return
示例2: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'-int', '--interface', type=str, help='interface to change')
parser.add_argument(
'-ls', '--list', help='list available interfaces',
action='store_true')
args = parser.parse_args()
if len(sys.argv) == 1:
parser.print_help()
exit()
if args.list:
interfaces = localifs()
mac = {}
for i in range(0, len(interfaces)):
print interfaces[i][0], ":", get_mac(interfaces[i][0]), ":", \
interfaces[i][1]
exit()
mac = get_mac(args.interface)
print "[+] Old MAC Address is: ", mac
status = change_mac(args.interface, mac)
print "status: ", status
示例3: __init__
def __init__(self):
# ----------------- NIC INFO -----------------
self.os = platform.dist()[0]
# If system is "debian":
if self.os == 'debian':
self.hostname = socket.gethostname()
self.iface = ni.interfaces()[1]
self.ipaddress = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr']
self.subnet = ni.ifaddresses(self.iface)[ni.AF_INET][0]['netmask']
self.gateways = ni.gateways()['default'][ni.AF_INET][0]
# --- OS INFO ---------------------
self.os_ver = platform.dist()[1]
self.mac = ''.join('%012x' % get_mac())
self.ip_data = get_ip()
self.path_ip = '/etc/network/interfaces'
self.dns_file = '/etc/resolv.conf'
# If system is "Arch Linux":
else:
self.hostname = socket.gethostname()
self.iface = ni.interfaces()[1]
self.ipaddress = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr']
self.subnet = ni.ifaddresses(self.iface)[ni.AF_INET][0]['netmask']
self.gateways = ni.gateways()['default'][ni.AF_INET][0]
# --- OS INFO ---------------------
self.os_ver = platform.dist()[1]
self.mac = ''.join('%012x' % get_mac())
self.ip_data = get_ip()
self.path_ip = '/etc/netctl/eth0'
self.dns_file = '/etc/resolv.conf'
logger.debug('GET IP SETTING OK!')
示例4: mac_addr_info
def mac_addr_info():
"""Returns mac address.
"""
mac = get_mac()
if mac == get_mac(): # not random generated
hexa = '%012x' % mac
value = ':'.join(hexa[i:i+2] for i in range(0, 12, 2))
else:
value = None
return {'mac': value}
示例5: getScannerID
def getScannerID() :
from uuid import getnode as get_mac
# ScannerID pattern
scannerPattern = r"^[0-9]{1,15}"
if (re.match(scannerPattern, str(get_mac())) == None) :
return -1
print ("Scanner Id : " + str(get_mac()))
return str(get_mac())
示例6: get_speech
def get_speech(self, phrase):
if self.token == '':
self.token = self.get_token()
query = {'tex': phrase,
'lan': 'zh',
'tok': self.token,
'ctp': 1,
'cuid': str(get_mac())[:32],
'per': self.per
}
r = requests.post('http://tsn.baidu.com/text2audio',
data=query,
headers={'content-type': 'application/json'})
try:
r.raise_for_status()
if r.json()['err_msg'] is not None:
self._logger.critical('Baidu TTS failed with response: %r',
r.json()['err_msg'],
exc_info=True)
return None
except Exception:
pass
with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
f.write(r.content)
tmpfile = f.name
return tmpfile
示例7: mapfn
def mapfn(key, value):
import multiprocessing
from uuid import getnode as get_mac
# Можно собирать дополнительную информацию
count_cores = multiprocessing.cpu_count()
key2 = str(get_mac())
yield key2, count_cores
示例8: user_setup
def user_setup(ip, port=None, user=None, password=None, root=None): # TODO IP PORT
if not user:
print 'TODO'
user=raw_input("Enter your username: ")
else:
try:
nick = get_mac()
data = {"username": user, "root_dir": root, "nick": str(nick),
"is_syncing": True, "password": password, 'last_sync': "0"}
path = os.path.expanduser('~') + '/.onedirclient/client.json'
conf_folder = os.path.expanduser('~') + '/.onedirclient'
if not os.path.exists(conf_folder):
os.mkdir(conf_folder)
with open(path, 'w') as filename:
json.dump(data, filename)
watch_folder = os.path.expanduser('~') + '/OneDirFiles'
if not os.path.exists(watch_folder):
os.mkdir(watch_folder)
# ftpclient = OneDirFtpClient(ip, port, user, nick, password, root)
db = conf_folder + '/sync.db'
ta = TableAdder(db, 'local')
ta.add_column('time')
ta.add_column('cmd')
ta.add_column('line')
ta.commit()
# print 3
except:
print 'invalid credentials'
示例9: __init__
def __init__(self,Pins = [24,25,8,7],ip = "localhost", port = 1883, clientId = "MQTT2StepperMotor", user = "driver", password = "1234", prefix = "StepperMotor"):
mosquitto.Mosquitto.__init__(self,clientId)
MotorControl.__init__(self,Pins)
#Get mac adress.
mac = get_mac()
#Make a number based on pins used.
pinid = ""
for pin in Pins:
pinid += "%02i" % pin
self.prefix = prefix + "/" + str(mac) + "/" + pinid
self.ip = ip
self.port = port
self.clientId = clientId
self.user = user
self.password = password
if user != None:
self.username_pw_set(user,password)
#self.will_set( topic = "system/" + self.prefix, payload="Offline", qos=1, retain=True)
self.will_set( topic = self.prefix, payload="Offline", qos=1, retain=True)
print "Connecting to:" +ip
self.connect(ip,keepalive=10)
self.subscribe(self.prefix + "/#", 0)
self.on_connect = self.mqtt_on_connect
self.on_message = self.mqtt_on_message
#self.publish(topic = "system/"+ self.prefix, payload="Online", qos=1, retain=True)
self.publish(topic = self.prefix, payload="Online", qos=1, retain=True)
示例10: __init__
def __init__(self, *argv, **kwargs):
super(RobotDaemon, self).__init__(*argv, **kwargs)
syslog.syslog(syslog.LOG_DEBUG, "%s" % config.path)
self.hwaddr = get_mac()
self.ip = get_ip()
self.uid = get_uid()
syslog.syslog(syslog.LOG_DEBUG, 'IP: %s, MAC: %s, UID: %s' % (self.ip, self.hwaddr, self.uid))
示例11: machineMeasureRun
def machineMeasureRun(jobFlowToM, nothing):
#debugLog('proc', 'machineMeasureRun. jobFlowToM:', jobFlowToM)
#EvalLog('{0:6f},104,start machineMeasure for jobFlows {1}'.format(time.time(), jobFlowToM))
totalCpu = psutil.cpu_percent(interval=0.05)
totalMemory = psutil.virtual_memory().total
hostId = str(get_mac())
for jobFlow in jobFlowToM:
measureResults = []
sourceJob = agentManager.sourceJobTable[jobFlow]
for name in sourceJob.measureStats:
if name == 'hostId':
measureResults.append(hostId)
elif name == 'totalCPU':
measureResults.append(totalCpu)
elif name == 'totalMemory':
measureResults.append(totalMemory)
elif name == 'IP':
measureResults.append(SelfIP.GetSelfIP())
if measureResults:
#debugLog('proc', 'measureResults:', measureResults)
(jobId, flowId) = decomposeKey(jobFlow)
(_, goFunc) = agentManager.eventAndGoFunc[jobId][flowId]
goThread = Thread(target=runGo, args=(goFunc, measureResults, jobId, flowId))
goThread.daemon = True
goThread.start()
#EvalLog('{0:6f},105,done one round of machineMeasure for jobFlows {1}'.format(time.time(), jobFlowToM))
agentManager.measureLatency += '#DoneOneRoundMachineMeasure${0:6f}'.format(time.time())
示例12: loadDeviceId
def loadDeviceId():
mac = str(get_mac())
global deviceId
global deviceIdTable
newlines=[]
try:
deviceId=deviceIdTable[mac]
except:
try:
with open(deviceIdfilename) as f:
print("lineread")
lineread = f.readlines()
print lineread
print lineread[0].split(':')[1]
print("ESCRBI LA CONCHA DE LA LORA")
deviceIdTable[mac]=lineread[0].split(':')[1]
print(deviceIdTable[mac])
print("ESCRIBI")
deviceId=deviceIdTable[mac]
except :
deviceId=str(request_DeviceId(mac))
try:
os.remove(deviceIdfilename)
except:
print("No hace falta borrarlo, el archivo no existe")
print(deviceId)
idfile=open(deviceIdfilename,'wb+')
newlines.append(mac)
newlines.append(":")
newlines.append(deviceId)
idfile.writelines(newlines)
idfile.close()
示例13: callback
def callback(ch, method, properties, body):
global sessionId
try:
sessionId = uuid.uuid1()
deviceMac = get_mac()
deviceMac = ':'.join(("%012X" % deviceMac)[i:i+2] for i in range(0, 12, 2))
logMsg = 'Fetching Speed Test request configuratin for device '+deviceMac
processMessage(logMsg, remotelog=False)
request = getSpeedTestRequest(deviceMac)
if request == None:
raise ValueError('Unable to get speed test request configuration!')
else:
rqId = request['request']['rqid']
logMsg = 'Speed device has been plugged in. Initiating speed test process...'
processMessage(logMsg, rqid=rqId)
#Retry if unsuccessful
if waitForPing("8.8.8.8", rqid=rqId) and speedtest(request):
updateRequestStatus(rqId, 3)
logMsg = 'Speed Test Completed!'
processMessage(logMsg, rqid=rqId)
else:
logMsg = 'Speed Test Unsuccessful!'
processMessage(logMsg, severity='critical', rqid=rqId)
except Exception as e:
syslogger(str(e), 'critical')
raise
示例14: __init__
def __init__(self, host, port, queue, timeout=60, conffile="/etc/notify-multiplexer/notify-multiplexer.conf"):
threading.Thread.__init__(self)
self.host = host
self.port = port
self.uid = get_mac()
self.connected = False
self.pingSem = threading.Semaphore()
self.daemon = True
self.timeout = timeout
self.queue = queue
self.config = configparser.SafeConfigParser()
self.conffile = conffile
# read config into object
try:
self.config.read(conffile)
except IOError as e:
logging.fatal("Issues loading config file: " + conf + ": " + repr(e.strerror) + ", bailing.")
exit(1)
self.context = self.makeSSLContext()
self.pingThread = NotifyMultiplexReciever._connManager._pingManager(self.pingSem, self, self.timeout)
self.pingThread.start()
logging.info("Initalized")
示例15: __init__
def __init__(self):
self.transID = b''
self.macaddr = b''
self.op = b''
self.CIADDR = b''
self.YIADDR = b''
self.SIADDR = b''
self.GIADDR = b''
self.DHCP_Message_Type = b''
self.Subnet_Mask = b''
self.Router = b''
self.Leas_Time = b''
self.DHCP_Server = b''
self.Dns_Server = set()
mac = bin(get_mac())[2:]
if len(mac) < 48:
mac = '0' + mac
for i in range(0, 48, 8):
self.macaddr += struct.pack('!B', int(mac[i:i+8], 2))
for i in range(4):
self.transID += struct.pack('!B', randint(0, 255))