def iBot(i): wireless = Wireless(['wlan0']) link="https://rajayalla98.pythonanywhere.com/get" if i == 9: if wireless.connect(ssid='I-Bot', password='******'): time.sleep(100) print wireless.current() response = urllib2.urlopen('http://11.11.11.11/') html = response.read() humidity,temperature = html.split("....") print humidity,temperature return temperature,humidity else: print "Did not connect" return [tem,hum] elif i == 19: if wireless.connect(ssid='Dont ask me', password='******'): data = {'temperature':tem,'humidity':hum} time.sleep(10) print wireless.current() requests.get(link,params=data) return [tem,hum] else: print "Did not connect" return [tem,hum] else: print "in loop" return [tem,hum]
def main(): import argparse parser = argparse.ArgumentParser("A watcher for ping") parser.add_argument("--testing", action="store_true") args = parser.parse_args() logging.basicConfig(level=logging.DEBUG if args.testing else logging.INFO) client = ActivityWatchClient("aw-watcher-network", testing=args.testing) bucketname = "{}_{}".format(client.client_name, client.client_hostname) eventtype = "ping" client.create_bucket(bucketname, eventtype) logger.info("Starting to log ping") while True: t = datetime.utcnow() sleeptime = 60 - (t.second + t.microsecond / 1000000.0) sleep(sleeptime) timestamp = datetime.now(pytz.utc) wifiname = Wireless().current() try: out = ping(30) client.send_events(bucketname, createEvents(out, timestamp, wifiname)) logger.info("Sent events") except Exception as e: import sys, traceback traceback.print_exc() logger.error("Exception thrown while pinging {}".format(e))
def main(): wireless = Wireless() print("Switching to GoPro SSID={}...".format(Config.GoPro.SSID)) wireless.connect(ssid=Config.GoPro.SSID, password=Config.GoPro.SSID_PASS) print("Connected to GoPro SSID") sleep(2) # sleep since it takes time for network connection to establish print("Connecting to GoPro...") gopro = GoProCamera.GoPro() print("GoPro connected") print("Downloading media...") media = gopro.downloadAll(media_type=Config.MEDIA_TYPE, dest_folder=Config.MEDIA_DEST_FOLDER) print("Download complete") if (Config.GoPro.is_power_off_when_done): print("Powering off GoPro...") gopro.power_off() print("GoPro powered off") print("Switching to Home SSID={}...".format(Config.HomeNetwork.SSID)) wireless.connect(ssid=Config.HomeNetwork.SSID, password=Config.HomeNetwork.SSID_PASS) print("Connected to Home SSID") sleep(2) print("Starting upload to Google Photos...") googlephotos.upload_folder(os.path.abspath(Config.MEDIA_DEST_FOLDER), album=Config.GooglePhotos.DEST_ALBUM, auth_file=Config.GooglePhotos.CREDENTIALS_PATH) print("Upload to Google Photos complete")
def connect_wifi(wifi='WIFI'): """ Connect WiFi network Args: wifi (str) WIFI or GOPRO, indicate wich wifi use. Returns: Void Raises: idk yet. """ from wireless import Wireless W = Wireless() W.interface() if wifi == 'WIFI': W.connect(ssid=_.WIFI_SSID, password=_.WIFI_PASS) elif wifi == 'GOPRO': W.connect(ssid=_.GOPRO_WIFI, password=_.GOPRO_PASS) else: print('No option!') return False
def Connect(): #Conectar a una red option=raw_input("\n Desea Conectarse a alguna red? \n s=Si n=No \n" ) yes= "s" or "S" no= "n" or "N" if option == yes: ssid=raw_input("\n Ingrese el SSID de la red\n") password=raw_input("\n Contrasenna\n") from wireless import Wireless wireless = Wireless() wireless.connect(ssid=ssid, password=password) if wireless : print "\n Conexion establecida" else: print "\n No se pudo conectar a la red, verifique el SSID y la contrasena ingresada" elif option==no: pass else: print "\n Ingrese una opcion correcta" Connect()
def get_wifi_devs(): try: from wireless import Wireless w = Wireless() return w.interfaces() except: return []
class WirelessUser(models.Model): wifi = Wireless() name = models.CharField(max_length=50, default="Home") ssid = models.CharField(max_length=20) password = models.CharField(max_length=20) is_on = models.BooleanField(default=False) def __str__(self): return self.name def start_wifi_check(self): self.is_on = self.have_internet() return self.is_on def connectus(self): self.is_on = self.wifi.connect(ssid=self.ssid, password=self.password) print("First try...") if self.is_on == False: print("Second try...") self.is_on = self.wifi.connect(ssid=self.ssid, password=self.password) if self.is_on == True: print(self.ssid, self.password) print("run worker") #sleep(2) os.system('sudo supervisorctl start motherworker') self.save() return self.is_on def wifi_check(self): #print (self.wifi.current()) #if self.wifi.current() == None: if self.have_internet() != True: if self.is_on == True: os.system('sudo supervisorctl stop motherworker') self.is_on = False else: if self.is_on == False: self.is_on = True os.system('sudo supervisorctl start motherworker') self.save() return self.is_on def have_internet(self): conn = httplib.HTTPConnection('www.google.com', timeout=5) try: conn.request("HEAD", "/") conn.close() print("We have true internet") return True except: conn.close() print("No internet connection!") return False def refresh_worker(self): os.system('sudo supervisorctl stop motherworker') os.system('sudo supervisorctl start motherworker') print("worker has been restarted!")
def __init__(self, socket=None): self.socket = socket #used to switch connection self.connectionManager = Wireless() #array of drone initializer self.drones = {'Solo Gold': None, 'Solo Green': None}
def network_connect(): print "connecting to ssid: Ashwin" wireless = Wireless() res = wireless.connect(ssid='Ashwin', password='') if not res: print "error connectingi to Ashwin..." print "connected. continue..."
def getMyMac(): try: wireless = Wireless() ifaces = wireless.interfaces() iface = ifaces[-1] mac = (netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr']) return mac except: print("Please manually select your interface using ifconfig or ipconfig using the -i flag") sys.exit(-1)
def showImage(self): data = self.lineEdit.text() text = self.comboBox.currentText() wireless = Wireless() wireless.connect(ssid=text,password=data) self.stackedWidget.setCurrentIndex(1) #p = Process(target=self.serverthread,args=()) #p.start() start_new_thread(self.serverthread,()) self.stop_thread_signal.connect(self.changeDisplay)
def get_networks(self): wireless = Wireless() ifs = wireless.interfaces() if len(ifs) == 0: return [] res = [] for c in Cell.all(ifs[0]): res.append(c.ssid) return res
def connect_wifi(ssid: str, password: Optional[str] = None) -> bool: UTIL_LOGGER.debug(f"connecting to {ssid}") if sys.platform == 'linux': from wireless import Wireless return Wireless().connect(ssid=ssid, password=password) elif sys.platform == 'win32' or sys.platform == 'cygwin': import winwifi return winwifi.WinWiFi.connect(ssid) else: UTIL_LOGGER.error(f"Can't auto-connect to wifi on {sys.platform}") return False
def __init__(self): self.disp = Display(Pin(DC), Pin(RES), Pin(CS), W, H, B) self.disp.show_progress('Start', 3) self.th = TempHumi(Pin(DHT)) self.sgp = CO2TVOC(Pin(SCL), Pin(SDA)) self.wireless = Wireless(WIFI_NAME, WIFI_PASSWORD) self.datetime = DateTime(self.wireless) self.logger = Logger(LOG_FILENAME) self.logger.write_startlog('\nSTART\n') self.pubcli = MQTT_CLI(self.wireless, MQTT_CLIENT_NAME, MQTT_SEVER_IP) self._count = 0 self._boarder_state = True
def callback(self): if 'wifi_list' not in self.mongo_document: def blacklisted(iface): """ Checks if interface starts with - smoothie - mon """ return iface.startswith('smoothie') or iface.startswith('mon') ifaces = [a for a in Wireless().interfaces() if not blacklisted(a)] self.update({'$set': {'wifi_list': ifaces}}) self.stop()
def authenticateWifi(ssid, password): signal.signal(signal.SIGALRM, handler) signal.alarm( 20) #Set the parameter to the amount of seconds you want to wait try: #RUN CODE HERE wireless = Wireless() wireless.connect(ssid, password) except: pass #print(2) signal.alarm(20) #Resets the alarm to 30 new seconds signal.alarm(0) #Disables the alarm
def send_alert(message=' ⚠️ *Error* al conectarse con la GoPro', telf=_.DEFAULT_TELF): from twilio.rest import Client from wireless import Wireless from util import _constants as _ w = Wireless() w.interface() wf = w.connect(ssid=_.WIFI_SSID, password=_.WIFI_PASS) client = Client(account_sid, auth_token) message = client.messages.create(from_='whatsapp:+14155238886', body=message, to='whatsapp:{}'.format(telf)) print(message.sid)
def drone_connect(): print "connecting to drone..." wireless = Wireless() res = wireless.connect(ssid='ardrone2_047592', password='') if not res: print "error connecting..." return print "connected. starting telnet" HOST = "192.168.1.1" tn = telnetlib.Telnet(HOST) command = 'killall udhcpd; iwconfig ath0 mode managed essid "Ashwin"; ifconfig ath0 192.168.43.50 netmask 255.255.255.0 up;' tn.write(command) tn.write("exit\n")
def __init__(self, socket=None): self.socket = socket self.dronesName = ["Solo Gold", "Solo Green"] self.wifiConnections = { 'Solo Gold': ['SoloLink_gold', 'sololinkmst'], 'Solo Green': ['SoloLink_MST', 'sololinkmst'] } #used to switch connection self.conn = Wireless() #array of drones initializer self.drones = { 'Solo Gold': drone.Drone('Solo Gold', self.wifiConnections['Solo Gold']), 'Solo Green': drone.Drone('Solo Green', self.wifiConnections['Solo Green']) }
def get_currently_connected_ap_ssid(): # strip() trims the trailing newline character # Typically, decode-strip-split will convert the raw check_output() like # b'wlan0 ESSID:"NyankoLab-2.4G"\n' # into # ['wlan0', 'ESSID:"NyankoLab-2.4G"'] # stdout = subprocess.check_output(['iwgetid']).decode('utf-8').strip().split() # logging.info(f'Wi-Fi AP info: {stdout}') # if len(stdout) < 2: # return '' # essid_and_name = stdout[1].split(':') # if len(essid_and_name) < 2: # logging.warn(f'iwgetid returned SSID info in an unexpected format: {stdout}') # return '' # ssid = essid_and_name[1].strip('"') # return ssid if 0 < len(ssid) else None w = Wireless() ssid = w.current() logging.info(f'Current ssid: {ssid}') return ssid
def measure_once(): for SSID in SSIDS: device_start_ts = time.time() # Connect device to access point wireless = Wireless() ap_start_ts = time.time() wireless.connect(SSID, PASSWORD) ap_stop_ts = time.time() # Connect client to node s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_start_ts = time.time() s.connect((TCP_IP, TCP_PORT)) socket_stop_ts = time.time() send_start_ts = time.time() s.send(MESSAGE) send_stop_ts = time.time() device_stop_ts = time.time() s.close() ap_delay_ms = (ap_stop_ts - ap_start_ts) * 1000 socket_delay_ms = (socket_stop_ts - socket_start_ts) * 1000 send_delay_ms = (send_stop_ts - send_start_ts) * 1000 device_delay_ms = (device_stop_ts - device_start_ts) * 1000 print("AP " + SSID + ": start: " + str(ap_start_ts)) print("AP " + SSID + ": stop: " + str(ap_stop_ts)) print("AP " + SSID + ": delay: " + str(ap_delay_ms)) print("Socket " + SSID + ": start: " + str(socket_start_ts)) print("Socket " + SSID + ": stop: " + str(socket_stop_ts)) print("Socket " + SSID + ": delay: " + str(socket_delay_ms)) print("Send " + SSID + ": start: " + str(send_start_ts)) print("Send " + SSID + ": stop: " + str(send_stop_ts)) print("Send " + SSID + ": delay: " + str(send_delay_ms)) print("Device " + SSID + ": start: " + str(device_start_ts)) print("Device " + SSID + ": stop: " + str(device_stop_ts)) print("Device " + SSID + ": delay: " + str(device_delay_ms)) ap_measurements.append(ap_delay_ms) socket_measurements.append(socket_delay_ms) send_measurements.append(send_delay_ms) device_measurements.append(device_delay_ms)
def getNetwork(): """Tries to discover the name of the current network, first the network interface but then the name of the WiFi network, if no WiFi network is present, it will return the name of the network interface. If there is no default route and thus no Internet then it will return an empty string.""" gws = netifaces.gateways() # Need to make sure the default route exists. if gws['default'] != {}: defaultGW = gws['default'][netifaces.AF_INET] currentNetwork = defaultGW[1] else: # If the above is true, there is no default route return "" # Now we need to check to see if we're on a WiFi network or not. w = Wireless() wName = w.current() if not wName is None: currentNetwork = wName return currentNetwork
def __init__(self, event): super().__init__() self.stopped = event self.count = 0 self.wlan_count_found = 0 self.wireless_module = Wireless() self.wlan_name_found_to_connect = "" self.wlan_name_found_to_connect_time = 999999999999 # defines a hotspot object with the ssid "Test Wlan" and the password from the constants, # ssid will be changed later. Because of a known bug, the hotspot is stopped once before the start. self.access_point = pyaccesspoint.AccessPoint( ssid="Test Wlan", password=const.Connection.WLAN_PASSWORD) self.access_point.stop() self.hotspot_status = False self.own_wlan_name_from_hotspot = "parknet" self.own_wlan_time_from_hotspot = 9999999999999 self.last_wlan_connected = "unset" self.block_list = []
def checkNetwork(ssid): timeout = 20 sleeptime = 5 loop = 0 while loop < timeout: wireless = Wireless() s = wireless.current() # Connected to a wifi network if s is not None: # Total network if s == ssid: print("+-[Connected] to {}".format(ssid)) return True # Another wifi network else: return True else: print("+-[Not connected] to {}. Waiting 5s to retry".format(ssid)) time.sleep(sleeptime) loop += 1 return False
self.status = "Off" print "Apagar" return # Hacemos las asignaciones de los pines fisicos pin_rele = 25 # Establecemos el valor del TOKEN facilitado por The BotFather TOKEN = "289317488:AAEpHlZCmDrndtD_zxbFp1YVkQXuDgZ9zFc" # Creamos una instancia tipo rele para el enchufe plug = rele(pin_rele) # Creamos objeto para manejar estado de la conexion wifi = Wireless() # Creamos conexion con bot de telegram bot = telebot.TeleBot(TOKEN) # Definimos identificadores de usuarios cesar_id = 9519882 # Definimos funcion para comprobar la identidad de los usuarios def check_security(message): print message.chat.username print message.from_user.id print message.chat.id if message.chat.type == "group": return True
from wireless import Wireless import wifi import time import socket wifilist = [] wireless=Wireless() interface=wireless.interface() Zentri_ssid_string='ZentriOS' def Search(): cells = wifi.Cell.all(interface) for cell in cells: wifilist.append(cell) return wifilist def FindFromSearchList(ssid): wifilist = Search() for cell in wifilist: if ssid in cell.ssid: return cell return False def FindFromSavedList(ssid): cell = wifi.Scheme.find(interface, ssid)
def is_connected_to_network(): """Check to see if connected to WeyeFeye network with name like 'WeyeFeyeb17d8a'""" w = Wireless() network_name = w.current() connected = bool(network_name and "WeyeFeye" in network_name) return connected
def configure(): wireless = Wireless() wireless_interfaces = wireless.interfaces() if not len(wireless_interfaces): print('Wireless interface could not be found on your device.') return None elif len(wireless_interfaces) > 1: while True: print("Choose interface: ") for i in range(0, len(wireless_interfaces)): print("{}: {}".format(str(i), wireless_interfaces[i])) try: wireless_interface_number = int((input("Enter number: "))) except: continue if wireless_interface_number >= len(wireless_interfaces): continue wlan = wireless_interfaces[wireless_interface_number] break else: wlan = wireless_interfaces[0] print('Wlan interface found: {}'.format(wlan)) remaining_interfaces = netifaces.interfaces() remaining_interfaces.remove(wlan) if not len(remaining_interfaces): inet = None print( 'No network nic could be found on your deivce to interface with the LAN' ) else: while True: print("Choose interface: ") for i in range(0, len(remaining_interfaces)): print("{}: {}".format(str(i), remaining_interfaces[i])) print("X: Do not use forwarding") try: remaining_interface_number = input("Enter number: ") if remaining_interface_number.lower() == "x": inet = None break remaining_interface_number = int(remaining_interface_number) except: continue if remaining_interface_number >= len(remaining_interfaces): continue inet = remaining_interfaces[remaining_interface_number] break while True: ip = input('Enter an IP address for your ap [192.168.45.1]:') ip = '192.168.45.1' if ip == '' else ip if not validate_ip(ip): continue break netmask = '255.255.255.0' ssid = input('Enter SSID [MyHotspot]:') ssid = 'MyHotspot' if ssid == '' else ssid password = input('Enter password [1234567890]:') password = '******' if password == '' else password encryption = input('Enter encryption [free]:') encryption = 'free' if encryption == '' else encryption return create_config_json(wlan, inet, ip, netmask, ssid, encryption, password)
import requests as r import json import time import datetime import os from fake_useragent import UserAgent #--- wireless module only works in linux ---# linux = False if linux: from wireless import Wireless wire = Wireless() #--- wifi setting ---# # By using various wifi, we can use various IP! wifi = [ "iptime","Redmi"] pw = ["00000000","12345678"] wifiNum=len(wifi) #--- running setting ---# ticker = "krw-btc" # be careful with the form! from_ = "2013-04-10 00:00:00" to_ = "2019-07-28 00:00:00" dataSaveFolder = "./minutesData" dataSaveFile = "./minutesData/"+ticker+".csv"
networkID = networks[0]['id'] orgID = organizations[0]['id'] # Retrieve list of devices devices = dashboard.networks.getNetworkDevices(networkID) numDevices = len(devices) # print(json.dumps(devices, indent=2)) snapshot = {} # Gather config snapshot of each device for i in range(numDevices): deviceInfo = devices[i] deviceType = deviceInfo['model'][0:2] # Call appropriate function depending on device type if deviceType == "MR": device = Wireless(deviceInfo['serial'], networkID, apiKey) identifier = "MR:" + deviceInfo['serial'] snapshot[identifier] = device.collectInfo() elif deviceType == "MS": device = Switch(deviceInfo['serial'], networkID, apiKey) identifier = "MS:" + deviceInfo['serial'] snapshot[identifier] = device.collectInfo() elif deviceType == "MX": device = Appliance(deviceInfo['serial'], networkID, orgID, apiKey) identifier = "MX:" + deviceInfo['serial'] snapshot[identifier] = device.collectInfo() device = TotalNetwork(networkID, apiKey) identifier = "Network" #snapshot = {} snapshot[identifier] = device.collectInfo()