Unsure how to phrase this, as I am new to Python.
Basically, I have this method in Python (below) that is scanning for devices available on my network. The Python code returns only 6 devices, and not the one I am searching for (Roku)
def scanner(self):
"""
Method that scans the network for available IP addresses.
"""
if len(self.ip) == 0:
network = '192.168.1.0/24'
else:
network = self.ip + '/24'
print("Scanning please wait...")
nm = nmap.PortScanner()
nm.scan(hosts=network, arguments='-sn')
host_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]
for item in nm.all_hosts():
print(item)
for host, status in host_list:
self.ip_addresses.append(host)
self.choose_address()
When I use sudo nmap -sn 192.168.1.0/24 in my terminal, I get back 9 devices, including the Roku. Does anyone have any insight into why this doesn't want to work for me?
Related
I have a problem. So, i connected 3 huawei e303 modems to my computer. I can see their interfaces and IPs that were given them by system. Here is an example
`modems = []
modem_temp = modem_sys()
for temp in interfaces():
addr = ifaddresses(temp)
if addr.get(AF_INET, None):
if '58:2c:80' in addr[AF_INET][0]['addr']: # 58:2c:80 is huawei
modem_temp.set_ip_adress(addr[AF_INET][0]['addr'])
print(modem_temp.ip_adress)
modem_temp.set_modem_interface(temp)
print(modem_temp.modem_interface)
modems.append(modem_temp)`
Where modem_sys is my class that contains only info about modem.
Output is:
169.254.169.233 {E549A313-E2CF-489A-A08B-A263CA7CBDB0}
192.168.1.100 {F3477F61-FC2D-4752-9FD9-0CF76529EA60}
169.254.170.23 {6F59AD83-A773-4D24-BF01-24FE7D9B6723}
But I can use to execute xml commands only 1 modem, because i can do them only on 192.168.1.1 address. So how can simultaniously use all modems to execute xml-commands? For example, after detecting modems, print device info by response = requests.get('http://192.168.1.1/api/device/information'). I'm using python3. I will be very appriciate for any help.
I am very new to Python. So in newboston's latest python tutorial Im making a web crawler. This Python script however only works on Linux. What would be the windows alternative to the following code?
import os
def get_ip_address(url):
command = "host " + url
process = os.popen(command)
results = str(process.read())
marker = results.find('has address') + 12
return results[marker:].splitlines()[0]
print(get_ip_address('google.com'))
I want it in the same format as I want to code multiple modules(i.e. get ip, who is etc.) and put them together as one Python program.
I am trying to obtain ONLY the ip address and nothing else in the results.
Alternatively, This is what I have for Windows so far:
import socket
def get_ips_for_host(url):
try:
ips = socket.gethostbyname_ex(url)
except socket.gaierror:
ips = []
return ips
ips = get_ips_for_host('www.facebook.com')
print(repr(ips))
How can i modify it to make it get only the IP address?
Similarly how can I get the nmap scan and the 'who is'?
the_ip = get_ips_for_host('www.facebook.com')[-1][0]
Im trying to make a algorithm in python to detect if my phone is in the area. Im using this to find my device:
bluetooth.discover_devices()
But it only detects my phone if I set my Bluetooth on my phone to "visible".
Is there a function or command to detect my phone when it's set to hidden?
Im fairly new to python so any form of help is very welcome!
Thanks in advance!
You could attempt to connect to your phone. If it's nearby, the connection will succeed. Devices can be connectable when they are not discoverable. You would have to already know the device address of your phone (via discovery when your phone was visible) in order to initiate the connection.
Not sure if a solution is still needed (I think this is right, just haven't been succesful with it). A book entitled "Violent Python" gives a solution for this in chapter 5, but I haven't been successful in implementing it. Supposedly you just need to increment the MAC address of the devices wifi adapter by one to calculate the Bluetooth MAC.
def retBtAddr(addr):
btAddr=str(hex(int(addr.replace(':', ''), 16) + 1))[2:]
btAddr=btAddr[0:2]+":"+btAddr[2:4]+":"+btAddr[4:6]+":"+\
btAddr[6:8]+":"+btAddr[8:10]+":"+btAddr[10:12]
return btAddr
and then something like the following (where OUI is the first 24 bytes of BT MAC)
def checkBluetooth(btAddr):
btName = lookup_name(btAddr)
if btName:
print '[+] Detected Bluetooth Device: ' + btName
else:
print '[-] Failed to Detect Bluetooth Device.'
def wifiPrint(pkt):
iPhone_OUI = 'd0:23:db'
if pkt.haslayer(Dot11):
wifiMAC = pkt.getlayer(Dot11).addr2
if wifiMAC != None and iPhone_OUI == wifiMAC[:8]:
print '[*] Detected iPhone MAC: ' + wifiMAC
btAddr = retBtAddr(wifiMAC)
print '[+] Testing Bluetooth MAC: ' + btAddr
checkBluetooth(btAddr)
On my linux machine, 1 of 3 network interfaces may be actually connected to the internet. I need to get the IP address of the currently connected interface, keeping in mind that my other 2 interfaces may be assigned IP addresses, just not be connected.
I can just ping a website through each of my interfaces to determine which one has connectivity, but I'd like to get this faster than waiting for a ping time out. And I'd like to not have to rely on an external website being up.
Update:
All my interfaces may have ip addresses and gateways. This is for an embedded device. So we allow the user to choose between say eth0 and eth1. But if there's no connection on the interface that the user tells us to use, we fall back to say eth2 which (in theory) will always work.
So what I need to do is first check if the user's selection is connected and if so return that IP. Otherwise I need to get the ip of eth2. I can get the IPs of the interfaces just fine, it's just determining which one is actually connected.
If the default gateway for the system is reliable, then grab that from the output from route -n the line that contains " UG " (note the spaces) will also contain the IP of the gateway and interface name of the active interface.
the solution is here : http://code.activestate.com/recipes/439093-get-names-of-all-up-network-interfaces-linux-only/
import fcntl
import array
import struct
import socket
import platform
"""
global constants. If you don't like 'em here,
move 'em inside the function definition.
"""
SIOCGIFCONF = 0x8912
MAXBYTES = 8096
def localifs():
"""
Used to get a list of the up interfaces and associated IP addresses
on this machine (linux only).
Returns:
List of interface tuples. Each tuple consists of
(interface name, interface IP)
"""
global SIOCGIFCONF
global MAXBYTES
arch = platform.architecture()[0]
# I really don't know what to call these right now
var1 = -1
var2 = -1
if arch == '32bit':
var1 = 32
var2 = 32
elif arch == '64bit':
var1 = 16
var2 = 40
else:
raise OSError("Unknown architecture: %s" % arch)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * MAXBYTES)
outbytes = struct.unpack('iL', fcntl.ioctl(
sock.fileno(),
SIOCGIFCONF,
struct.pack('iL', MAXBYTES, names.buffer_info()[0])
))[0]
namestr = names.tostring()
return [(namestr[i:i+var1].split('\0', 1)[0], socket.inet_ntoa(namestr[i+20:i+24])) \
for i in xrange(0, outbytes, var2)]
print localifs()
I have my web page in python, I am able to get the IP address of the user, who will be accessing our web page, we want to get the mac address of the user's PC, is it possible in python, we are using Linux PC, we want to get it on Linux.
I have a small, signed Java Applet, which requires Java 6 runtime on the remote computer to do this. It uses the getHardwareAddress() method on NetworkInterface to obtain the MAC address. I use javascript to access a method in the applet that calls this and returns a JSON object containing the address. This gets stuffed into a hidden field in the form and posted with the rest of the fields.
from Active code
#!/usr/bin/env python
import ctypes
import socket
import struct
def get_macaddress(host):
""" Returns the MAC address of a network host, requires >= WIN2K. """
# Check for api availability
try:
SendARP = ctypes.windll.Iphlpapi.SendARP
except:
raise NotImplementedError('Usage only on Windows 2000 and above')
# Doesn't work with loopbacks, but let's try and help.
if host == '127.0.0.1' or host.lower() == 'localhost':
host = socket.gethostname()
# gethostbyname blocks, so use it wisely.
try:
inetaddr = ctypes.windll.wsock32.inet_addr(host)
if inetaddr in (0, -1):
raise Exception
except:
hostip = socket.gethostbyname(host)
inetaddr = ctypes.windll.wsock32.inet_addr(hostip)
buffer = ctypes.c_buffer(6)
addlen = ctypes.c_ulong(ctypes.sizeof(buffer))
if SendARP(inetaddr, 0, ctypes.byref(buffer), ctypes.byref(addlen)) != 0:
raise WindowsError('Retreival of mac address(%s) - failed' % host)
# Convert binary data into a string.
macaddr = ''
for intval in struct.unpack('BBBBBB', buffer):
if intval > 15:
replacestr = '0x'
else:
replacestr = 'x'
macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '')])
return macaddr.upper()
if __name__ == '__main__':
print 'Your mac address is %s' % get_macaddress('localhost')
All you can access is what the user sends to you.
MAC address is not part of that data.
The dpkt package was already mentioned on SO. It allows for parsing TCP/IP packets. I have not yet used it for your case, though.