Problem with using Win32 IPHelper API in python - python

I'm attempting to create python module for getting network parameters. I'm using ctypes and has some problems.
Function __getInterfaces_win2k() works with python 2.5 and 2.6, but doesn't work with python 2.7 (Unhandled exception at 0x1e001759 in python.exe: 0xC0000005: Access violation reading location 0x00000010.)
Function __getInterfaces_win_after_win2k() doesn't work in any version of python (same error).
Sometimes, before the crash program print the necessary information. I've tried compare practically all values with program in C. Everything is normal. Any help much appreciated.
'''
Get different network parameters (interfaces, routing table, etc)
'''
from platform import system
from sys import getwindowsversion
def getInterfaces():
if system() == 'Windows':
winversion = getwindowsversion()
#from table on page OSVERSIONINFO Structure for GetVersionEx Function
if winversion[0] > 5 or (winversion[0] == 5 and winversion[1] > 0):
return __getInterfaces_win_after_win2k()
else:
return __getInterfaces_win2k()
else:
pass
MAX_ADAPTER_ADDRESS_LENGTH = 8
def __getInterfaces_win_after_win2k():
import ctypes.wintypes
class HEADER_STRUCT(ctypes.Structure):
_fields_ = [
("Length", ctypes.c_ulong),
("IfIndex", ctypes.c_ulong)]
class HEADER_UNION(ctypes.Union):
_fields_ = [
("Alignment", ctypes.c_ulonglong),
("HEADER_STRUCT", HEADER_STRUCT)]
class SOCKADDR(ctypes.Structure):
_fields_ = [
("sa_family", ctypes.c_ushort),
("sa_data", ctypes.c_byte * 14)]
PSOCKADDR = ctypes.POINTER(SOCKADDR)
class SOCKET_ADDRESS(ctypes.Structure):
_fields_ = [
("pSockaddr", PSOCKADDR),
("iSockaddrLength", ctypes.c_int)]
class IP_ADAPTER_UNICAST_ADDRESS(ctypes.Structure):
pass
PIP_ADAPTER_UNICAST_ADDRESS = ctypes.POINTER(IP_ADAPTER_UNICAST_ADDRESS)
IP_ADAPTER_UNICAST_ADDRESS._fields_ = [
("length", ctypes.c_ulong),
("flags", ctypes.c_ulong),
("next", PIP_ADAPTER_UNICAST_ADDRESS),
("address", SOCKET_ADDRESS),
("prefixOrigin", ctypes.c_int),
("suffixOrigin", ctypes.c_int),
("dadState", ctypes.c_int),
("validLifetime", ctypes.c_ulong),
("preferredLifetime", ctypes.c_ulong),
("leaseLifetime", ctypes.c_ulong),
("onLinkPrefixLength", ctypes.c_byte)]
class IP_ADAPTER_ANYCAST_ADDRESS(ctypes.Structure):
pass
PIP_ADAPTER_ANYCAST_ADDRESS = ctypes.POINTER(IP_ADAPTER_ANYCAST_ADDRESS)
IP_ADAPTER_ANYCAST_ADDRESS._fields_ = [
("alignment", ctypes.c_ulonglong),
("next", PIP_ADAPTER_ANYCAST_ADDRESS),
("address", SOCKET_ADDRESS)]
class IP_ADAPTER_MULTICAST_ADDRESS(ctypes.Structure):
pass
PIP_ADAPTER_MULTICAST_ADDRESS = ctypes.POINTER(IP_ADAPTER_MULTICAST_ADDRESS)
IP_ADAPTER_MULTICAST_ADDRESS._fields_ = [
("alignment", ctypes.c_ulonglong),
("next", PIP_ADAPTER_MULTICAST_ADDRESS),
("address", SOCKET_ADDRESS)]
class IP_ADAPTER_DNS_SERVER_ADDRESS(ctypes.Structure):
pass
PIP_ADAPTER_DNS_SERVER_ADDRESS = ctypes.POINTER(IP_ADAPTER_DNS_SERVER_ADDRESS)
IP_ADAPTER_DNS_SERVER_ADDRESS._fields_ = [
("alignment", ctypes.c_ulonglong),
("next", PIP_ADAPTER_DNS_SERVER_ADDRESS),
("address", SOCKET_ADDRESS)]
class IP_ADAPTER_PREFIX(ctypes.Structure):
pass
PIP_ADAPTER_PREFIX = ctypes.POINTER(IP_ADAPTER_PREFIX)
IP_ADAPTER_PREFIX._fields_ = [
("alignment", ctypes.c_ulonglong),
("next", PIP_ADAPTER_PREFIX),
("address", SOCKET_ADDRESS),
("prefixLength", ctypes.c_ulong)]
class IP_ADAPTER_WINS_SERVER_ADDRESS(ctypes.Structure):
pass
PIP_ADAPTER_WINS_SERVER_ADDRESS = ctypes.POINTER(IP_ADAPTER_WINS_SERVER_ADDRESS)
IP_ADAPTER_WINS_SERVER_ADDRESS._fields_ = [
("alignment", ctypes.c_ulonglong),
("next", PIP_ADAPTER_WINS_SERVER_ADDRESS),
("address", SOCKET_ADDRESS)]
class IP_ADAPTER_GATEWAY_ADDRESS(ctypes.Structure):
pass
PIP_ADAPTER_GATEWAY_ADDRESS = ctypes.POINTER(IP_ADAPTER_GATEWAY_ADDRESS)
IP_ADAPTER_GATEWAY_ADDRESS._fields_ = [
("alignment", ctypes.c_ulonglong),
("next", PIP_ADAPTER_GATEWAY_ADDRESS),
("address", SOCKET_ADDRESS)]
#ifdef.h
class NET_LUID(ctypes.Structure):
_fields_ = [
("value", ctypes.c_ulonglong)]
class GUID(ctypes.Structure):
_fields_ = [
("data1", ctypes.wintypes.DWORD),
("data2", ctypes.wintypes.WORD),
("data3", ctypes.wintypes.WORD),
("data4", ctypes.c_byte * 8)]
MAX_DNS_SUFFIX_STRING_LENGTH = 256
class IP_ADAPTER_DNS_SUFFIX(ctypes.Structure):
pass
PIP_ADAPTER_DNS_SUFFIX = ctypes.POINTER(IP_ADAPTER_DNS_SUFFIX)
IP_ADAPTER_DNS_SUFFIX._fields_ = [
("next", PIP_ADAPTER_DNS_SUFFIX),
("string", ctypes.c_wchar * MAX_DNS_SUFFIX_STRING_LENGTH)]
class IP_ADAPTER_ADDRESSES(ctypes.Structure):
pass
PIP_ADAPTER_ADDRESSES = ctypes.POINTER(IP_ADAPTER_ADDRESSES)
MAX_DHCPV6_DUID_LENGTH = 130 #IPTypes.h
IP_ADAPTER_ADDRESSES._fields_ = [
("header", HEADER_UNION),
("next", PIP_ADAPTER_ADDRESSES),
("adapterName", ctypes.c_char_p),
("firstUnicastAddress", PIP_ADAPTER_UNICAST_ADDRESS),
("firstAnycastAddress", PIP_ADAPTER_ANYCAST_ADDRESS),
("firstMulticastAddress", PIP_ADAPTER_MULTICAST_ADDRESS),
("firstDnsServerAddress", PIP_ADAPTER_DNS_SERVER_ADDRESS),
("dnsSuffix", ctypes.c_wchar_p),
("description", ctypes.c_wchar_p),
("friendlyName", ctypes.c_wchar_p),
("physicalAddress", ctypes.c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),
("physicalAddressLength", ctypes.wintypes.DWORD),
("flags", ctypes.wintypes.DWORD),
("mtu", ctypes.wintypes.DWORD),
("ifType", ctypes.wintypes.DWORD),
("operStatus", ctypes.c_int),
("ipv6IfIndex", ctypes.wintypes.DWORD),
("zoneIndices", ctypes.wintypes.DWORD * 16),
("firstPrefix", PIP_ADAPTER_PREFIX),
("transmitLinkSpeed", ctypes.c_ulonglong),
("receiveLinkSpeed", ctypes.c_ulonglong),
("firstWinsServerAddress", PIP_ADAPTER_WINS_SERVER_ADDRESS),
("firstGatewayAddress", PIP_ADAPTER_GATEWAY_ADDRESS),
("ipv4Metric", ctypes.c_ulong),
("ipv6Metric", ctypes.c_ulong),
("luid", NET_LUID),#ifdef.h
("dhcpv4Server", SOCKET_ADDRESS),
("compartmentId", ctypes.c_uint32),#ifdef.h
("networkGuid", GUID),
("connectionType", ctypes.c_int),
("tunnelType", ctypes.c_int),
("dhcpv6Server", SOCKET_ADDRESS),
("dhcpv6ClientDuid", ctypes.c_byte * MAX_DHCPV6_DUID_LENGTH),
("dhcpv6ClientDuidLength", ctypes.c_ulong),
("dhcpv6Iaid", ctypes.c_ulong)]
GetAdaptersAddresses = ctypes.windll.iphlpapi.GetAdaptersAddresses
GetAdaptersAddresses.restype = ctypes.c_ulong
GetAdaptersAddresses.argtypes = [
ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p,
PIP_ADAPTER_ADDRESSES, ctypes.POINTER(ctypes.c_ulong)]
outBufLen = ctypes.c_ulong(15000)
adapters = ctypes.pointer(IP_ADAPTER_ADDRESSES())
ctypes.resize(adapters, outBufLen.value)
from socket import AF_INET
GAA_FLAG_INCLUDE_PREFIX = ctypes.c_ulong(0x0010)
GetAdaptersAddresses(ctypes.c_ulong(AF_INET), GAA_FLAG_INCLUDE_PREFIX, None,
adapters, ctypes.byref(outBufLen))
a = adapters[0]
ifaces = {}
while a:
iface = {}
iface['desc'] = a.description
# iface['mac'] = ':'.join(["%02X" % part for part in a.address])
#
# adNode = a.ipAddressList
# iface['ip'] = []
# while True:
# ipAddr = adNode.ipAddress
# if ipAddr:
# iface['ip'].append( (ipAddr, adNode.ipMask) )
# if adNode.next:
# adNode = adNode.next.contents
# else:
# break
ifaces[a.adapterName] = iface
if a.next:
a = a.next.contents
else:
break
return ifaces
def __getInterfaces_win2k():
import ctypes.wintypes
MAX_ADAPTER_NAME_LENGTH = 256
MAX_ADAPTER_DESCRIPTION_LENGTH = 128
class IP_ADDR_STRING(ctypes.Structure):
pass
LP_IP_ADDR_STRING = ctypes.POINTER(IP_ADDR_STRING)
IP_ADDR_STRING._fields_ = [
("next", LP_IP_ADDR_STRING),
("ipAddress", ctypes.c_char * 16),
("ipMask", ctypes.c_char * 16),
("context", ctypes.wintypes.DWORD)]
class IP_ADAPTER_INFO (ctypes.Structure):
pass
LP_IP_ADAPTER_INFO = ctypes.POINTER(IP_ADAPTER_INFO)
IP_ADAPTER_INFO._fields_ = [
("next", LP_IP_ADAPTER_INFO),
("comboIndex", ctypes.wintypes.DWORD),
("adapterName", ctypes.c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),
("description", ctypes.c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),
("addressLength", ctypes.c_uint),
("address", ctypes.c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),
("index", ctypes.wintypes.DWORD),
("type", ctypes.c_uint),
("dhcpEnabled", ctypes.c_uint),
("currentIpAddress", LP_IP_ADDR_STRING),
("ipAddressList", IP_ADDR_STRING),
("gatewayList", IP_ADDR_STRING),
("dhcpServer", IP_ADDR_STRING),
("haveWins", ctypes.c_uint),
("primaryWinsServer", IP_ADDR_STRING),
("secondaryWinsServer", IP_ADDR_STRING),
("leaseObtained", ctypes.c_ulong),
("leaseExpires", ctypes.c_ulong)]
GetAdaptersInfo = ctypes.windll.iphlpapi.GetAdaptersInfo
GetAdaptersInfo.restype = ctypes.wintypes.DWORD
GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, ctypes.POINTER(ctypes.c_ulong)]
adapters = ctypes.pointer(IP_ADAPTER_INFO())
buflen = ctypes.c_ulong(ctypes.sizeof(IP_ADAPTER_INFO))
GetAdaptersInfo(adapters, ctypes.byref(buflen))
ctypes.resize(adapters, buflen.value)
GetAdaptersInfo(adapters, ctypes.byref(buflen))
a = adapters.contents
ifaces = {}
while a:
iface = {}
iface['desc'] = a.description
iface['mac'] = ':'.join(["%02X" % part for part in a.address])
adNode = a.ipAddressList
iface['ip'] = []
while True:
ipAddr = adNode.ipAddress
if ipAddr:
iface['ip'].append( (ipAddr, adNode.ipMask) )
if adNode.next:
adNode = adNode.next.contents
else:
break
ifaces[a.adapterName] = iface
if a.next:
a = a.next.contents
else:
break
return ifaces
if __name__ == "__main__":
ifaces = getInterfaces()
for k, v in ifaces.iteritems():
print k
for k2, v2 in v.iteritems():
print '\t', k2, v2

don't know if this is the cause of your problem, but the last field of the NET_LUID structure seems to be missing: the 64 bit wide "Info" structure. Also the last field of the IP_ADAPTER_ADDRESSES structure (FirstDnsSuffix) is missing, but that only matters on a W2k8 server - I guess you are using this code for Vista or XP.

I can't find any info on the python version changes of the byte size of the ctypes, but I encountered a problem considering the IP_ADAPTER_INFO structure and the time_t size.
Solution can be found here http://social.msdn.microsoft.com/forums/en-US/vcgeneral/thread/fe17ff48-71e4-401b-9982-84addb809eea.
So maybe change the lines
("leaseObtained", ctypes.c_ulong)
("leaseExpires", ctypes.c_ulong)
to
("leaseObtained", ctypes.c_uint)
("leaseExpires", ctypes.c_uint)

you can found ctypes Python functional for Windows networking in http://code.google.com/p/pywingui/source/browse/#svn/trunk/pywingui/network
and examples http://code.google.com/p/pywingui/source/browse/#svn/trunk/pywingui_tests

Related

Python win32api keybd_event: How do I input a string of characters?

I used the below to get the Window Handle of an app and bring it to be the focus. I want to type in a string of characters into the app. But using win32api.keybd_event, I am able to type in only single characters? Is there a way to type in a string of characters?
Eg, "I am happy"
Thank you
import win32gui
import win32api
import win32con
hld = win32gui.FindWindow (None, "UNTITLED") # Returns the handle of the window titled UNTITLED
if hld>0:
win32gui.SetForegroundWindow(hld)
win32api.keybd_event(0x46, 0, ) # F
You can use the SendInput function to achieve this. Send the string you need to send to the corresponding window once through this function.
I created a sample as follows:
import ctypes as ct
from win32con import SW_MINIMIZE, SW_RESTORE
from win32ui import FindWindow, error as ui_err
from time import sleep
class cls_KeyBdInput(ct.Structure):
_fields_ = [
("wVk", ct.c_ushort),
("wScan", ct.c_ushort),
("dwFlags", ct.c_ulong),
("time", ct.c_ulong),
("dwExtraInfo", ct.POINTER(ct.c_ulong) )
]
class cls_HardwareInput(ct.Structure):
_fields_ = [
("uMsg", ct.c_ulong),
("wParamL", ct.c_short),
("wParamH", ct.c_ushort)
]
class cls_MouseInput(ct.Structure):
_fields_ = [
("dx", ct.c_long),
("dy", ct.c_long),
("mouseData", ct.c_ulong),
("dwFlags", ct.c_ulong),
("time", ct.c_ulong),
("dwExtraInfo", ct.POINTER(ct.c_ulong) )
]
class cls_Input_I(ct.Union):
_fields_ = [
("ki", cls_KeyBdInput),
("mi", cls_MouseInput),
("hi", cls_HardwareInput)
]
class cls_Input(ct.Structure):
_fields_ = [
("type", ct.c_ulong),
("ii", cls_Input_I)
]
def make_input_objects( l_keys ):
p_ExtraInfo_0 = ct.pointer(ct.c_ulong(0))
l_inputs = [ ]
for n_key, n_updown in l_keys:
ki = cls_KeyBdInput( n_key, 0, n_updown, 0, p_ExtraInfo_0 )
ii = cls_Input_I()
ii.ki = ki
l_inputs.append( ii )
n_inputs = len(l_inputs)
l_inputs_2=[]
for ndx in range( 0, n_inputs ):
s2 = "(1, l_inputs[%s])" % ndx
l_inputs_2.append(s2)
s_inputs = ', '.join(l_inputs_2)
cls_input_array = cls_Input * n_inputs
o_input_array = eval( "cls_input_array( %s )" % s_inputs )
p_input_array = ct.pointer( o_input_array )
n_size_0 = ct.sizeof( o_input_array[0] )
return ( n_inputs, p_input_array, n_size_0 )
def send_input( window1, t_inputs,):
tpl1 = window1.GetWindowPlacement()
window1.SetForegroundWindow()
sleep(0.2)
window1.SetFocus()
sleep(0.2)
rv = ct.windll.user32.SendInput( *t_inputs )
return rv
def test():
#t_hello is "hello\n"
t_hello = ( ( 0x48, 0 ), ( 0x45, 0 ), ( 0x4C, 0 ), ( 0x4C, 0 ), ( 0x4F, 0 ), ( 0x0D, 0 ), )
l_keys = [ ]
l_keys.extend( t_hello )
s_app_name = "Notepad"
window1 = FindWindow( s_app_name, None )
if window1 == None:
print( "%r has no window." % s_app_name )
input( 'press enter to close' )
exit()
t_inputs = make_input_objects( l_keys )
n = send_input( window1, t_inputs )
if __name__ == '__main__':
test()
This sample implements sending the string "hello" to the notepad. And it works fine for me.

Python ctypes Windows operations - script fails in 64bit interpreter, but works fine in 32bit interpreter

The following piece of code uses only standard libraries, and runs without an error in a 32bit Python 3.6 interpreter, but returns an error in a 64bit one (Windows handle is invalid):
import ctypes, ctypes.wintypes
INVALID_HANDLE_VALUE = -1
DIGCF_PRESENT = 0x00000002
DIGCF_DEVICEINTERFACE = 0x00000010
ERROR_INSUFFICIENT_BUFFER = 122
ERROR_NO_MORE_ITEMS = 259
MAXIMUM_USB_STRING_LENGTH = 255
kernel32 = ctypes.windll.kernel32
setupapi = ctypes.windll.setupapi
SetupDiGetClassDevs = setupapi.SetupDiGetClassDevsW
SetupDiEnumDeviceInterfaces = setupapi.SetupDiEnumDeviceInterfaces
SetupDiGetDeviceInterfaceDetail = setupapi.SetupDiGetDeviceInterfaceDetailW
CM_Get_Parent = setupapi.CM_Get_Parent
CM_Get_Device_ID = setupapi.CM_Get_Device_IDW
CM_Request_Device_Eject = setupapi.CM_Request_Device_EjectW
class GUID(ctypes.Structure):
_fields_ = [("Data1", ctypes.c_ulong),
("Data2", ctypes.c_ushort),
("Data3", ctypes.c_ushort),
("Data4", ctypes.c_ubyte * 8)]
def __str__(self):
return '{%08X-%04X-%04X-%04X-%012X}' % (
self.Data1, self.Data2, self.Data3,
self.Data4[0] * 256 + self.Data4[1],
self.Data4[2] * (256 ** 5) +
self.Data4[3] * (256 ** 4) +
self.Data4[4] * (256 ** 3) +
self.Data4[5] * (256 ** 2) +
self.Data4[6] * 256 +
self.Data4[7])
class SP_DEVINFO_DATA(ctypes.Structure):
_fields_ = [("cbSize", ctypes.wintypes.DWORD),
("ClassGuid", GUID),
("DevInst", ctypes.wintypes.DWORD),
("Reserved", ctypes.c_void_p)
]
class SP_DEVICE_INTERFACE_DATA(ctypes.Structure):
_fields_ = [("cbSize", ctypes.wintypes.DWORD),
("InterfaceClassGuid", GUID),
("Flags", ctypes.wintypes.DWORD),
("Reserved", ctypes.c_void_p)
]
class SP_DEVICE_INTERFACE_DETAIL_DATA(ctypes.Structure):
_fields_ = [("cbSize", ctypes.wintypes.DWORD),
("DevicePath", ctypes.c_wchar*255)]
GUID_DEVINTERFACE_VOLUME = GUID(0x53F5630D, 0xB6BF, 0x11D0,
(ctypes.c_ubyte*8)(0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B))
hDevInfo = SetupDiGetClassDevs(ctypes.byref(GUID_DEVINTERFACE_VOLUME),
0,
0,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)
if hDevInfo == INVALID_HANDLE_VALUE:
print(ctypes.windll.GetLastError(), ctypes.windll.FormatError())
def get_device_interface(i, device=None):
interfaceData = SP_DEVICE_INTERFACE_DATA()
interfaceData.cbSize = ctypes.sizeof(SP_DEVICE_INTERFACE_DATA)
if SetupDiEnumDeviceInterfaces(
hDevInfo,
device and ctypes.byref(device) or None,
ctypes.byref(GUID_DEVINTERFACE_VOLUME),
i,
ctypes.byref(interfaceData)):
return interfaceData
elif ctypes.GetLastError() == ERROR_NO_MORE_ITEMS:
return
else:
print(ctypes.GetLastError(), ctypes.FormatError())
def connected_devices():
interface_index = 0
interface = get_device_interface(interface_index)
devices = connected_devices()
I suspect that the issue is not strictly a Python problem, but rather a difference in how 64 and 32 bit interpreter types interact with Windows.
Can anyone explain why this is happening?

Setting proxy settings in Windows with Python (using InternetSetOption)

I have written a little script that needs to be able to enable and disable proxy settings with Python. Right now I edit the registry to achieve this, but it doesn't seem to work on all versions of windows, so I would much rather use InternetSetOption. Information about the API is really scarce and most of the examples are in C, which I don't know:
https://support.microsoft.com/en-us/kb/226473
It would probably look somewhat like this (this snippet is actually for refreshing the browser proxy settings):
import ctypes
INTERNET_OPTION_REFRESH = 37
INTERNET_OPTION_SETTINGS_CHANGED = 39
internet_set_option = ctypes.windll.Wininet.InternetSetOptionW
internet_set_option(0, 38, 0, 0)
internet_set_option(0, INTERNET_OPTION_REFRESH, 0, 0)
internet_set_option(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
I actually figured this out myself, through lots of trial and errors. Working example:
from ctypes import *
from ctypes.wintypes import *
LPWSTR = POINTER(WCHAR)
HINTERNET = LPVOID
INTERNET_PER_CONN_PROXY_SERVER = 2
INTERNET_OPTION_REFRESH = 37
INTERNET_OPTION_SETTINGS_CHANGED = 39
INTERNET_OPTION_PER_CONNECTION_OPTION = 75
INTERNET_PER_CONN_PROXY_BYPASS = 3
INTERNET_PER_CONN_FLAGS = 1
class INTERNET_PER_CONN_OPTION(Structure):
class Value(Union):
_fields_ = [
('dwValue', DWORD),
('pszValue', LPWSTR),
('ftValue', FILETIME),
]
_fields_ = [
('dwOption', DWORD),
('Value', Value),
]
class INTERNET_PER_CONN_OPTION_LIST(Structure):
_fields_ = [
('dwSize', DWORD),
('pszConnection', LPWSTR),
('dwOptionCount', DWORD),
('dwOptionError', DWORD),
('pOptions', POINTER(INTERNET_PER_CONN_OPTION)),
]
def set_proxy_settings(ip, port, on=True):
if on:
setting = create_unicode_buffer(ip+":"+str(port))
else:
setting = None
InternetSetOption = windll.wininet.InternetSetOptionW
InternetSetOption.argtypes = [HINTERNET, DWORD, LPVOID, DWORD]
InternetSetOption.restype = BOOL
List = INTERNET_PER_CONN_OPTION_LIST()
Option = (INTERNET_PER_CONN_OPTION * 3)()
nSize = c_ulong(sizeof(INTERNET_PER_CONN_OPTION_LIST))
Option[0].dwOption = INTERNET_PER_CONN_FLAGS
Option[0].Value.dwValue = (2 if on else 1) # PROXY_TYPE_DIRECT Or
Option[1].dwOption = INTERNET_PER_CONN_PROXY_SERVER
Option[1].Value.pszValue = setting
Option[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS
Option[2].Value.pszValue = create_unicode_buffer("localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;172.32.*;192.168.*")
List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST)
List.pszConnection = None
List.dwOptionCount = 3
List.dwOptionError = 0
List.pOptions = Option
InternetSetOption(None, INTERNET_OPTION_PER_CONNECTION_OPTION, byref(List), nSize)
InternetSetOption(None, INTERNET_OPTION_SETTINGS_CHANGED, None, 0)
InternetSetOption(None, INTERNET_OPTION_REFRESH, None, 0)
set_proxy_settings("127.0.0.1", 52042)

open a string in notepad at runtime in python

I have a string called 's' and I want to open it in notepad at runtime without saving it in/as a file. Is there any way to achieve this in python?
There is an example here.
#### Script to try to write something down in notepad
import win32api
import win32gui
import win32con
import time
import subprocess
#start notepad.exe asynchronously
subprocess.Popen('Notepad.exe')
# get the window handle of the blank, minimized notepad window
hwnd = win32gui.FindWindowEx(0, 0, 0, "Untitled - Notepad")
# print it just for kicks
print hwnd
win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
#this restores the proper window, so we know we have correct handle
#just to give it a little pause
time.sleep(2)
print "trying to post message"
#try to send it a return key
win32api.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
win32api.SendMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
#the above generates absolutely no effect on the notepad window.
#same effect no matter what vk code i use (e.g. 65 for A, VK_SPACE for space, etc)
#### end of script
May I suggest you to use AutoIt3 facilities (http://www.autoitscript.com/autoit3/docs/tutorials/notepad/notepad.htm "AutoIt Notepad Tutorial")
AutoIt3 is a Windows scripting language to control quite anything in Windows. It provide a COM API so you can make integrate it in your Python script
from win32com.client import Dispatch
AutoIt = Dispatch("AutoItX3.Control")
AutoIt.Run('Notepad.exe')
AutoIt.WinWaitActive("Untitled - Notepad")
AutoIt.Send("This is some text.")
It may be also possible to use AutoHotKey (the fully GPL version of AutoIt)
Notepad has no facilities for doing such from an external source. Short of hooking into the Windows windowing API, finding the text area, and populating it yourself.
No. Notepad does not read data from stdin, so passing it a file or OS-level file-like is the only way for it to display text.
This code will send s into Notepad window from Python script.
class cls_KeyBdInput(ct.Structure):
_fields_ = [
("wVk", ct.c_ushort),
("wScan", ct.c_ushort),
("dwFlags", ct.c_ulong),
("time", ct.c_ulong),
("dwExtraInfo", ct.POINTER(ct.c_ulong) )
]
class cls_HardwareInput(ct.Structure):
_fields_ = [
("uMsg", ct.c_ulong),
("wParamL", ct.c_short),
("wParamH", ct.c_ushort)
]
class cls_MouseInput(ct.Structure):
_fields_ = [
("dx", ct.c_long),
("dy", ct.c_long),
("mouseData", ct.c_ulong),
("dwFlags", ct.c_ulong),
("time", ct.c_ulong),
("dwExtraInfo", ct.POINTER(ct.c_ulong) )
]
class cls_Input_I(ct.Union):
_fields_ = [
("ki", cls_KeyBdInput),
("mi", cls_MouseInput),
("hi", cls_HardwareInput)
]
class cls_Input(ct.Structure):
_fields_ = [
("type", ct.c_ulong),
("ii", cls_Input_I)
]
def make_input_objects( l_keys ):
p_ExtraInfo_0 = ct.pointer(ct.c_ulong(0))
l_inputs = [ ]
for n_key, n_updown in l_keys:
ki = cls_KeyBdInput( n_key, 0, n_updown, 0, p_ExtraInfo_0 )
ii = cls_Input_I()
ii.ki = ki
l_inputs.append( ii )
n_inputs = len(l_inputs)
l_inputs_2=[]
for ndx in range( 0, n_inputs ):
s2 = "(1, l_inputs[%s])" % ndx
l_inputs_2.append(s2)
s_inputs = ', '.join(l_inputs_2)
cls_input_array = cls_Input * n_inputs
o_input_array = eval( "cls_input_array( %s )" % s_inputs )
p_input_array = ct.pointer( o_input_array )
n_size_0 = ct.sizeof( o_input_array[0] )
# these are the args for user32.SendInput()
return ( n_inputs, p_input_array, n_size_0 )
def send_s( window1 ):
t_s = ( ( 0x53, 0 ), )
l_keys = [ ]
l_keys.extend( t_s )
t_inputs = make_input_objects( l_s )
win32gui.ShowWindow(window1, win32con.SW_SHOWNORMAL)
win32gui.SetForegroundWindow(window1)
rv = ct.windll.user32.SendInput( *t_inputs )
def find_window( s_app_name ):
try:
window1 = FindWindow( None, s_app_name,)
return window1
except ui_err:
pass
except:
raise
try:
window1 = FindWindow( s_app_name, None, )
return window1
except ui_err:
return None
except:
raise
def search_title(srch,ttls):
out=None
for i in range(len(ttls)):
#print i, ttls[i][1]
if srch in ttls[i][1]:
out= ttls[i][1]
return out
def get_window_titles():
titles = []
def foreach_window(hwnd, lParam):
if IsWindowVisible(hwnd):
length = GetWindowTextLength(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
GetWindowText(hwnd, buff, length + 1)
ttl=buff.value
titles.append((hwnd, ttl))
return True
EnumWindows(EnumWindowsProc(foreach_window), 0)
return titles
ttls=get_window_titles()
title=search_title('Notepad',ttls)
window1 = find_window( title )
send_s( window1)

How can I retrieve the signal strength of nearby wireless LAN networks on Windows using Python?

How can I retrieve the signal strength of nearby wireless LAN networks on Windows using Python?
I would like to either show or graph the values.
If you are on Windows, you probably want to use the WLAN API, which provides the 'WlanGetAvailableNetworkList()' function (see the API docs for usage). I am not aware of any python wrappers for WLANAPI.DLL so you may have to wrap it yourself using ctypes. I have a preliminary script that does this (works-for-me), but it may be crufty. You'll want to read the documentation to understand the meaning of all the fields:
from ctypes import *
from ctypes.wintypes import *
from sys import exit
def customresize(array, new_size):
return (array._type_*new_size).from_address(addressof(array))
wlanapi = windll.LoadLibrary('wlanapi.dll')
ERROR_SUCCESS = 0
class GUID(Structure):
_fields_ = [
('Data1', c_ulong),
('Data2', c_ushort),
('Data3', c_ushort),
('Data4', c_ubyte*8),
]
WLAN_INTERFACE_STATE = c_uint
(wlan_interface_state_not_ready,
wlan_interface_state_connected,
wlan_interface_state_ad_hoc_network_formed,
wlan_interface_state_disconnecting,
wlan_interface_state_disconnected,
wlan_interface_state_associating,
wlan_interface_state_discovering,
wlan_interface_state_authenticating) = map(WLAN_INTERFACE_STATE, range(0, 8))
class WLAN_INTERFACE_INFO(Structure):
_fields_ = [
("InterfaceGuid", GUID),
("strInterfaceDescription", c_wchar * 256),
("isState", WLAN_INTERFACE_STATE)
]
class WLAN_INTERFACE_INFO_LIST(Structure):
_fields_ = [
("NumberOfItems", DWORD),
("Index", DWORD),
("InterfaceInfo", WLAN_INTERFACE_INFO * 1)
]
WLAN_MAX_PHY_TYPE_NUMBER = 0x8
DOT11_SSID_MAX_LENGTH = 32
WLAN_REASON_CODE = DWORD
DOT11_BSS_TYPE = c_uint
(dot11_BSS_type_infrastructure,
dot11_BSS_type_independent,
dot11_BSS_type_any) = map(DOT11_BSS_TYPE, range(1, 4))
DOT11_PHY_TYPE = c_uint
dot11_phy_type_unknown = 0
dot11_phy_type_any = 0
dot11_phy_type_fhss = 1
dot11_phy_type_dsss = 2
dot11_phy_type_irbaseband = 3
dot11_phy_type_ofdm = 4
dot11_phy_type_hrdsss = 5
dot11_phy_type_erp = 6
dot11_phy_type_ht = 7
dot11_phy_type_IHV_start = 0x80000000
dot11_phy_type_IHV_end = 0xffffffff
DOT11_AUTH_ALGORITHM = c_uint
DOT11_AUTH_ALGO_80211_OPEN = 1
DOT11_AUTH_ALGO_80211_SHARED_KEY = 2
DOT11_AUTH_ALGO_WPA = 3
DOT11_AUTH_ALGO_WPA_PSK = 4
DOT11_AUTH_ALGO_WPA_NONE = 5
DOT11_AUTH_ALGO_RSNA = 6
DOT11_AUTH_ALGO_RSNA_PSK = 7
DOT11_AUTH_ALGO_IHV_START = 0x80000000
DOT11_AUTH_ALGO_IHV_END = 0xffffffff
DOT11_CIPHER_ALGORITHM = c_uint
DOT11_CIPHER_ALGO_NONE = 0x00
DOT11_CIPHER_ALGO_WEP40 = 0x01
DOT11_CIPHER_ALGO_TKIP = 0x02
DOT11_CIPHER_ALGO_CCMP = 0x04
DOT11_CIPHER_ALGO_WEP104 = 0x05
DOT11_CIPHER_ALGO_WPA_USE_GROUP = 0x100
DOT11_CIPHER_ALGO_RSN_USE_GROUP = 0x100
DOT11_CIPHER_ALGO_WEP = 0x101
DOT11_CIPHER_ALGO_IHV_START = 0x80000000
DOT11_CIPHER_ALGO_IHV_END = 0xffffffff
WLAN_AVAILABLE_NETWORK_CONNECTED = 1
WLAN_AVAILABLE_NETWORK_HAS_PROFILE = 2
WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES = 0x00000001
WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES = 0x00000002
class DOT11_SSID(Structure):
_fields_ = [
("SSIDLength", c_ulong),
("SSID", c_char * DOT11_SSID_MAX_LENGTH)
]
class WLAN_AVAILABLE_NETWORK(Structure):
_fields_ = [
("ProfileName", c_wchar * 256),
("dot11Ssid", DOT11_SSID),
("dot11BssType", DOT11_BSS_TYPE),
("NumberOfBssids", c_ulong),
("NetworkConnectable", c_bool),
("wlanNotConnectableReason", WLAN_REASON_CODE),
("NumberOfPhyTypes", c_ulong),
("dot11PhyTypes", DOT11_PHY_TYPE * WLAN_MAX_PHY_TYPE_NUMBER),
("MorePhyTypes", c_bool),
("wlanSignalQuality", c_ulong),
("SecurityEnabled", c_bool),
("dot11DefaultAuthAlgorithm", DOT11_AUTH_ALGORITHM),
("dot11DefaultCipherAlgorithm", DOT11_CIPHER_ALGORITHM),
("Flags", DWORD),
("Reserved", DWORD)
]
class WLAN_AVAILABLE_NETWORK_LIST(Structure):
_fields_ = [
("NumberOfItems", DWORD),
("Index", DWORD),
("Network", WLAN_AVAILABLE_NETWORK * 1)
]
WlanOpenHandle = wlanapi.WlanOpenHandle
WlanOpenHandle.argtypes = (DWORD, c_void_p, POINTER(DWORD), POINTER(HANDLE))
WlanOpenHandle.restype = DWORD
WlanEnumInterfaces = wlanapi.WlanEnumInterfaces
WlanEnumInterfaces.argtypes = (HANDLE, c_void_p,
POINTER(POINTER(WLAN_INTERFACE_INFO_LIST)))
WlanEnumInterfaces.restype = DWORD
WlanGetAvailableNetworkList = wlanapi.WlanGetAvailableNetworkList
WlanGetAvailableNetworkList.argtypes = (HANDLE, POINTER(GUID), DWORD, c_void_p,
POINTER(POINTER(WLAN_AVAILABLE_NETWORK_LIST)))
WlanGetAvailableNetworkList.restype = DWORD
WlanFreeMemory = wlanapi.WlanFreeMemory
WlanFreeMemory.argtypes = [c_void_p]
if __name__ == '__main__':
NegotiatedVersion = DWORD()
ClientHandle = HANDLE()
ret = WlanOpenHandle(1, None, byref(NegotiatedVersion), byref(ClientHandle))
if ret != ERROR_SUCCESS:
exit(FormatError(ret))
# find all wireless network interfaces
pInterfaceList = pointer(WLAN_INTERFACE_INFO_LIST())
ret = WlanEnumInterfaces(ClientHandle, None, byref(pInterfaceList))
if ret != ERROR_SUCCESS:
exit(FormatError(ret))
try:
ifaces = customresize(pInterfaceList.contents.InterfaceInfo,
pInterfaceList.contents.NumberOfItems)
# find each available network for each interface
for iface in ifaces:
print("Interface: {}".format(iface.strInterfaceDescription))
pAvailableNetworkList = pointer(WLAN_AVAILABLE_NETWORK_LIST())
ret = WlanGetAvailableNetworkList(ClientHandle,
byref(iface.InterfaceGuid),
0,
None,
byref(pAvailableNetworkList))
if ret != ERROR_SUCCESS:
exit(FormatError(ret))
try:
avail_net_list = pAvailableNetworkList.contents
networks = customresize(avail_net_list.Network,
avail_net_list.NumberOfItems)
for network in networks:
print("SSID: {}, quality: {:2d}%".format(
network.dot11Ssid.SSID[:network.dot11Ssid.SSIDLength].decode(),
network.wlanSignalQuality))
finally:
WlanFreeMemory(pAvailableNetworkList)
finally:
WlanFreeMemory(pInterfaceList)
On linux, you have a couple of choices:
The standard options is to parse the output of iwlist -scan. However, if you are currently connected to a wlan and not running as root, it only returns the currently connected wlan.
If you need more than this, the best way is to query the wireless manager daemon. On modern, linuxes, this is usually NetworkManager, although wicd is becoming more popular. Both of these managers can be queried using dbus. Unless you can control what the clients have on their systems, you might need to support both of these options, or at least one option and have a fallback for iwlist.
If you don't want to deal with Windows API you could use method shown here with a slight modification.
You can use this command:
netsh wlan show networks mode=Bssid
using this code
import subprocess
results = subprocess.check_output(["netsh", "wlan", "show", "network", "mode=Bssid"])
This will give you additiona "Signal" information as a percentage. This can be converted to RSSI using this method.
So.. I based myself on #fmarks code (which was a live-safer for me), and you should add the WlanScan function, or else the RSSI values will not refresh.
Here is my extended code!
All props to #fmarks!
__author__ = 'Pedro Gomes'
import time
from ctypes import *
from ctypes.wintypes import *
from sys import exit
def customresize(array, new_size):
return (array._type_*new_size).from_address(addressof(array))
wlanapi = windll.LoadLibrary('wlanapi.dll')
ERROR_SUCCESS = 0
class GUID(Structure):
_fields_ = [
('Data1', c_ulong),
('Data2', c_ushort),
('Data3', c_ushort),
('Data4', c_ubyte*8),
]
WLAN_INTERFACE_STATE = c_uint
(wlan_interface_state_not_ready,
wlan_interface_state_connected,
wlan_interface_state_ad_hoc_network_formed,
wlan_interface_state_disconnecting,
wlan_interface_state_disconnected,
wlan_interface_state_associating,
wlan_interface_state_discovering,
wlan_interface_state_authenticating) = map(WLAN_INTERFACE_STATE, xrange(0, 8))
class WLAN_INTERFACE_INFO(Structure):
_fields_ = [
("InterfaceGuid", GUID),
("strInterfaceDescription", c_wchar * 256),
("isState", WLAN_INTERFACE_STATE)
]
class WLAN_INTERFACE_INFO_LIST(Structure):
_fields_ = [
("NumberOfItems", DWORD),
("Index", DWORD),
("InterfaceInfo", WLAN_INTERFACE_INFO * 1)
]
WLAN_MAX_PHY_TYPE_NUMBER = 0x8
DOT11_SSID_MAX_LENGTH = 32
WLAN_REASON_CODE = DWORD
DOT11_BSS_TYPE = c_uint
(dot11_BSS_type_infrastructure,
dot11_BSS_type_independent,
dot11_BSS_type_any) = map(DOT11_BSS_TYPE, xrange(1, 4))
DOT11_PHY_TYPE = c_uint
dot11_phy_type_unknown = 0
dot11_phy_type_any = 0
dot11_phy_type_fhss = 1
dot11_phy_type_dsss = 2
dot11_phy_type_irbaseband = 3
dot11_phy_type_ofdm = 4
dot11_phy_type_hrdsss = 5
dot11_phy_type_erp = 6
dot11_phy_type_ht = 7
dot11_phy_type_IHV_start = 0x80000000
dot11_phy_type_IHV_end = 0xffffffff
DOT11_AUTH_ALGORITHM = c_uint
DOT11_AUTH_ALGO_80211_OPEN = 1
DOT11_AUTH_ALGO_80211_SHARED_KEY = 2
DOT11_AUTH_ALGO_WPA = 3
DOT11_AUTH_ALGO_WPA_PSK = 4
DOT11_AUTH_ALGO_WPA_NONE = 5
DOT11_AUTH_ALGO_RSNA = 6
DOT11_AUTH_ALGO_RSNA_PSK = 7
DOT11_AUTH_ALGO_IHV_START = 0x80000000
DOT11_AUTH_ALGO_IHV_END = 0xffffffff
DOT11_CIPHER_ALGORITHM = c_uint
DOT11_CIPHER_ALGO_NONE = 0x00
DOT11_CIPHER_ALGO_WEP40 = 0x01
DOT11_CIPHER_ALGO_TKIP = 0x02
DOT11_CIPHER_ALGO_CCMP = 0x04
DOT11_CIPHER_ALGO_WEP104 = 0x05
DOT11_CIPHER_ALGO_WPA_USE_GROUP = 0x100
DOT11_CIPHER_ALGO_RSN_USE_GROUP = 0x100
DOT11_CIPHER_ALGO_WEP = 0x101
DOT11_CIPHER_ALGO_IHV_START = 0x80000000
DOT11_CIPHER_ALGO_IHV_END = 0xffffffff
WLAN_AVAILABLE_NETWORK_CONNECTED = 1
WLAN_AVAILABLE_NETWORK_HAS_PROFILE = 2
WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES = 0x00000001
WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES = 0x00000002
class DOT11_SSID(Structure):
_fields_ = [
("SSIDLength", c_ulong),
("SSID", c_char * DOT11_SSID_MAX_LENGTH)
]
class WLAN_AVAILABLE_NETWORK(Structure):
_fields_ = [
("ProfileName", c_wchar * 256),
("dot11Ssid", DOT11_SSID),
("dot11BssType", DOT11_BSS_TYPE),
("NumberOfBssids", c_ulong),
("NetworkConnectable", c_bool),
("wlanNotConnectableReason", WLAN_REASON_CODE),
("NumberOfPhyTypes", c_ulong),
("dot11PhyTypes", DOT11_PHY_TYPE * WLAN_MAX_PHY_TYPE_NUMBER),
("MorePhyTypes", c_bool),
("wlanSignalQuality", c_ulong),
("SecurityEnabled", c_bool),
("dot11DefaultAuthAlgorithm", DOT11_AUTH_ALGORITHM),
("dot11DefaultCipherAlgorithm", DOT11_CIPHER_ALGORITHM),
("Flags", DWORD),
("Reserved", DWORD)
]
class WLAN_AVAILABLE_NETWORK_LIST(Structure):
_fields_ = [
("NumberOfItems", DWORD),
("Index", DWORD),
("Network", WLAN_AVAILABLE_NETWORK * 1)
]
DOT11_MAC_ADDRESS = c_ubyte * 6
DOT11_CIPHER_ALGORITHM = c_uint
DOT11_CIPHER_ALGO_NONE = 0x00
DOT11_CIPHER_ALGO_WEP40 = 0x01
DOT11_CIPHER_ALGO_TKIP = 0x02
DOT11_PHY_TYPE = c_uint
DOT11_PHY_TYPE_UNKNOWN = 0
DOT11_PHY_TYPE_ANY = 0
DOT11_PHY_TYPE_FHSS = 1
DOT11_PHY_TYPE_DSSS = 2
DOT11_PHY_TYPE_IRBASEBAND = 3
DOT11_PHY_TYPE_OFDM = 4
DOT11_PHY_TYPE_HRDSSS = 5
DOT11_PHY_TYPE_ERP = 6
DOT11_PHY_TYPE_HT = 7
DOT11_PHY_TYPE_IHV_START = 0X80000000
DOT11_PHY_TYPE_IHV_END = 0XFFFFFFFF
class WLAN_RATE_SET(Structure):
_fields_ = [
("uRateSetLength", c_ulong),
("usRateSet", c_ushort * 126)
]
class WLAN_BSS_ENTRY(Structure):
_fields_ = [
("dot11Ssid",DOT11_SSID),
("uPhyId",c_ulong),
("dot11Bssid", DOT11_MAC_ADDRESS),
("dot11BssType", DOT11_BSS_TYPE),
("dot11BssPhyType", DOT11_PHY_TYPE),
("lRssi", c_long),
("uLinkQuality", c_ulong),
("bInRegDomain", c_bool),
("usBeaconPeriod",c_ushort),
("ullTimestamp", c_ulonglong),
("ullHostTimestamp",c_ulonglong),
("usCapabilityInformation",c_ushort),
("ulChCenterFrequency", c_ulong),
("wlanRateSet",WLAN_RATE_SET),
("ulIeOffset", c_ulong),
("ulIeSize", c_ulong)]
class WLAN_BSS_LIST(Structure):
_fields_ = [
("TotalSize", DWORD),
("NumberOfItems", DWORD),
("NetworkBSS", WLAN_BSS_ENTRY * 1)
]
class WLAN_AVAILABLE_NETWORK_LIST_BSS(Structure):
_fields_ = [
("TotalSize", DWORD),
("NumberOfItems", DWORD),
("Network", WLAN_BSS_ENTRY * 1)
]
WlanOpenHandle = wlanapi.WlanOpenHandle
WlanOpenHandle.argtypes = (DWORD, c_void_p, POINTER(DWORD), POINTER(HANDLE))
WlanOpenHandle.restype = DWORD
WlanCloseHandle = wlanapi.WlanCloseHandle
WlanCloseHandle.argtypes = (HANDLE, c_void_p)
WlanCloseHandle.restype = DWORD
WlanEnumInterfaces = wlanapi.WlanEnumInterfaces
WlanEnumInterfaces.argtypes = (HANDLE, c_void_p,
POINTER(POINTER(WLAN_INTERFACE_INFO_LIST)))
WlanEnumInterfaces.restype = DWORD
WlanGetAvailableNetworkList = wlanapi.WlanGetAvailableNetworkList
WlanGetAvailableNetworkList.argtypes = (HANDLE, POINTER(GUID), DWORD, c_void_p,
POINTER(POINTER(WLAN_AVAILABLE_NETWORK_LIST)))
WlanGetAvailableNetworkList.restype = DWORD
WlanGetNetworkBssList = wlanapi.WlanGetNetworkBssList
WlanGetNetworkBssList.argtypes = (HANDLE, POINTER(GUID),POINTER(GUID),POINTER(GUID), c_bool, c_void_p,
POINTER(POINTER(WLAN_BSS_LIST)))
WlanGetNetworkBssList.restype = DWORD
WlanFreeMemory = wlanapi.WlanFreeMemory
WlanFreeMemory.argtypes = [c_void_p]
WlanScan = wlanapi.WlanScan
WlanScan.argtypes = (HANDLE, POINTER(GUID),c_void_p,c_void_p, c_void_p)
WlanScan.restype = DWORD
def get_interface():
NegotiatedVersion = DWORD()
ClientHandle = HANDLE()
ret = WlanOpenHandle(1, None, byref(NegotiatedVersion), byref(ClientHandle))
if ret != ERROR_SUCCESS:
exit(FormatError(ret))
# find all wireless network interfaces
pInterfaceList = pointer(WLAN_INTERFACE_INFO_LIST())
ret = WlanEnumInterfaces(ClientHandle, None, byref(pInterfaceList))
if ret != ERROR_SUCCESS:
exit(FormatError(ret))
try:
ifaces = customresize(pInterfaceList.contents.InterfaceInfo,
pInterfaceList.contents.NumberOfItems)
# find each available network for each interface
for iface in ifaces:
#print "Interface: %s" % (iface.strInterfaceDescription)
interface = iface.strInterfaceDescription
finally:
WlanFreeMemory(pInterfaceList)
return interface
class MAC_BSSID_POWER:
"""Classe para os valores retirados"""
def __init__(self, mac, bssid):
self.mac = str(mac)
self.bssid = str(bssid)
self.valores = []
def addPower(self,power):
self.valores.append(int(power))
def getBssid(self):
return self.bssid
def getPowers(self):
return self.valores
def getMac(self):
return self.mac
def get_BSSI():
BSSI_Values={}
NegotiatedVersion = DWORD()
ClientHandle = HANDLE()
ret = WlanOpenHandle(1, None, byref(NegotiatedVersion), byref(ClientHandle))
if ret != ERROR_SUCCESS:
exit(FormatError(ret))
# find all wireless network interfaces
pInterfaceList = pointer(WLAN_INTERFACE_INFO_LIST())
ret = WlanEnumInterfaces(ClientHandle, None, byref(pInterfaceList))
if ret != ERROR_SUCCESS:
exit(FormatError(ret))
try:
ifaces = customresize(pInterfaceList.contents.InterfaceInfo,
pInterfaceList.contents.NumberOfItems)
# find each available network for each interface
for iface in ifaces:
# print "Interface: %s" % (iface.strInterfaceDescription)
pAvailableNetworkList2 = pointer(WLAN_BSS_LIST())
ret2 = WlanGetNetworkBssList(ClientHandle,
byref(iface.InterfaceGuid),
None,
None,True,None,
byref(pAvailableNetworkList2))
if ret2 != ERROR_SUCCESS:
exit(FormatError(ret2))
try:
retScan = WlanScan(ClientHandle,byref(iface.InterfaceGuid),None,None,None)
if retScan != ERROR_SUCCESS:
exit(FormatError(retScan))
avail_net_list2 = pAvailableNetworkList2.contents
networks2 = customresize(avail_net_list2.NetworkBSS,
avail_net_list2.NumberOfItems)
for network in networks2:
SSID = str(network.dot11Ssid.SSID[:network.dot11Ssid.SSIDLength])
BSSID = ':'.join('%02x' % b for b in network.dot11Bssid).upper()
signal_strength = str(network.lRssi)
# print "SSID: " + SSID + " BSSID: "+ BSSID+ " SS: "+signal_strength
BSSI_Values[BSSID] = [SSID,signal_strength]
#print "Total "+str(len(networks2))
#print BSSI_Values
finally:
WlanFreeMemory(pAvailableNetworkList2)
WlanCloseHandle(ClientHandle,None)
finally:
WlanFreeMemory(pInterfaceList)
return BSSI_Values
def get_BSSI_times_and_total_seconds(times,seconds):
BSSI_to_return = {}
for i in range(0,seconds*times):
time_to_sleep = float(1.0/times)
time.sleep(time_to_sleep)
got_bssi_temp = get_BSSI()
for bssi in got_bssi_temp:
if not BSSI_to_return.get(bssi):
BSSI_to_return[bssi] = MAC_BSSID_POWER(bssi,got_bssi_temp[bssi][0])
BSSI_to_return[bssi].addPower( got_bssi_temp[bssi][1] )
#BSSI_to_return[bssi] = [got_bssi_temp[bssi][1]]
else:
BSSI_to_return[bssi].addPower( got_bssi_temp[bssi][1] )
#BSSI_to_return[bssi].append(got_bssi_temp[bssi][1])
print "Medicao "+str(i)+" de "+str(seconds*times)
print BSSI_to_return
return BSSI_to_return
if __name__ == '__main__':
#print get_interface()
import time
test = get_BSSI()
for i in range(0,10):
time.sleep(0.5)
oldTest = test
test = get_BSSI()
print "Teste: "+str(i)
if oldTest == test:
print "IGUAL"
else:
print "DIFERENTE"
print test
print "End"
#fmark I just wanted to say THANK YOU so much for this awesome post. At my work I have been trying to get RSSI from the connected AP in Windows, and you deserve many thanks for me finally getting it done. I'm currently listing all APs, but I'm working on modifying it. I wanted to offer a recommendation towards your code. I'm not very experienced with C or the Python CTypes module, but I think I might have found a possible bug. I'm really not sure what difference it makes, but I noticed:
You define enums like this:
DOT11_BSS_TYPE = c_uint
(dot11_BSS_type_infrastructure,
dot11_BSS_type_independent,
dot11_BSS_type_any) = map(DOT11_BSS_TYPE, xrange(1, 4))
But then other times you define something very similar like this:
DOT11_PHY_TYPE = c_uint
dot11_phy_type_unknown = 0
dot11_phy_type_any = 0
dot11_phy_type_fhss = 1
dot11_phy_type_dsss = 2
dot11_phy_type_irbaseband = 3
dot11_phy_type_ofdm = 4
dot11_phy_type_hrdsss = 5
dot11_phy_type_erp = 6
dot11_phy_type_ht = 7
dot11_phy_type_IHV_start = 0x80000000
dot11_phy_type_IHV_end = 0xffffffff
I think the second snippit should be modeled like the first, but I could be wrong. Here was my idea:
DOT11_PHY_TYPE = c_uint
(dot11_phy_type_unknown,
dot11_phy_type_any,
dot11_phy_type_fhss,
dot11_phy_type_dsss,
dot11_phy_type_irbaseband,
dot11_phy_type_ofdm,
dot11_phy_type_hrdsss,
dot11_phy_type_erp,
dot11_phy_type_ht,
dot11_phy_type_IHV_start,
dot11_phy_type_IHV_end) = map(DOT11_PHY_TYPE,
[0,0,1,2,3,4,
5,6,7,0x80000000,
0xffffffff])
This way those values would get correctly mapped to DOT11_PHY_TYPE. Perhaps I am completely wrong, but for future folks like myself, I just wanted whatever is stumbled on here to be correct :)
Thanks again, #fmark.

Categories