I'm trying to get all IP's and their associated MAC address from the network.
Till now, i have the following code:
eth = Ether(dst = "ff:ff:ff:ff:ff:ff")
arp = ARP(pdst = '198.13.13.1')
answered = srp1(eth / arp)
print answered[1].hwsrc
print answered[1].psrc
But this only gets me the MAC of what Ip i input.
I think i have to use:
answered, unanswered = srp(eth/arp)
And modify pdst with the address of the subnet but i don't know how to do it.
Any ideas?
You just need to enter your network as pdst field. You want to use a timeout because some probes probably won't get an answer. For example:
ans, unans = srp(Ether(dst=ETHER_BROADCAST) / ARP(pdst="198.13.13.0/24"), timeout=1)
Then you need to parse ans. If you want to get the MAC & IP addresses associated, you can create a list of tuples. For example:
res = [(pr.psrc, pr.hwsrc) for _, pr in ans]
print res
You can also use arping(), a specialized function for that purpose:
ans, unans = arping("198.13.13.0/24")
ans.show()
Related
My code is designed to geo-locate IP addresses from a text file. I'm having trouble on the last section. When I run the code, I get a complaint from the map_ip.update line: socket.error: illegal IP address string passed to inet_pton
When I troubleshoot with a print statement, I get the following format:
['$ ip address']
['$ ip address']
['$ ip address']
How do I get country_name_by_addr() to read each IP address in the proper format? It appears my IP addresses are being formatted as a list of strings in individual lists.
# script that geo-locates IP addresses from a consolidated dictionary
import pygeoip
import itertools
import re
# initialize dictionary for IP addresses
count = {}
"""
This loop reads text file line-by-line and
returns one-to-one key:value pairs of IP addresses.
"""
with open('$short_logins.txt path') as f:
for cnt, line in enumerate(f):
ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', line)
count.update({cnt: ip})
cnt += 1
"""
This line consolidates unique IP addresses. Keys represent how
many times each unique IP address occurs in the text file.
"""
con_count = [(k, len(list(v))) for k, v in itertools.groupby(sorted(count.values)))]
"""
Country lookup:
This section passes each unique IP address from con_count
through country name database. These IP address are not required
to come from con_count.
"""
map_ip = {}
gi = pygeoip.GeoIP('$GeoIP.dat path')
for i in count.itervalues():
map_ip.update({i: gi.country_name_by_addr(i)})
print map_ip
So I solved this dilemma yesterday by doing away with the regular expression:
ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', line)
I found a much simpler solution by stripping the whitespace in the file and checking to see if the IP address was accounted for. IP addresses are all in the third column hence the [2]:
ip = line.split()[2]
if ip in count:
count[ip] += 1
else:
count.update({ip: 1})
I removed the con_count line as well. Pygeoip functions are much more receptive to lists not made out of regular expressions.
I'm creating a SNMP program to list interfaces (with ip, mask and mac) of devices. I'm using NetSnmp to get the macaddress but the output looks like this ('\x00PV\xaf\x00v',)
This is the SNMP request:
oidmac = netsnmp.Varbind("ifPhysAddress."+i)
mac = netsnmp.snmpget(
oidmac,
Version = 2,
DestHost = sys.argv[2],
Community = sys.argv[1])
Info about the code ...
sys.argv[1] = Community string
sys.argv[2] = IP of the SNMP agent
i = a variable with the interface ID.
How can I convert the string to an MAC address in format aa:bb:cc:dd:11:22 ?
In Python2, it's very simple
>>> ":".join(x.encode('hex') for x in '\x00PV\xaf\x00v')
'00:50:56:af:00:76'
For Python3, you can try something like this
>>> "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*b'\x00PV\xaf\x00v')
'00:50:56:af:00:76'
Use :02X (capital X) if you want uppercase hex codes
I'm trying to retrieve ids of a specific set of keywords from pubmed using the following standard code,
import os
from Bio import Entrez
from Bio import Medline
#Defining keyword file
keywords_file = "D:\keywords.txt"
# Splitting keyword file into a list
keyword_list = []
keyword_list = open(keywords_file).read().split(',')
#print keyword_list
# Creating folders by keywords and creating a text file of the same keyword in each folder
for item in keyword_list:
create_file = item +'.txt.'
path = r"D:\Thesis"+'\\'+item
#print path
if not os.path.exists(path):
os.makedirs(path)
#print os.getcwd()
os.chdir(path)
f = open(item+'.txt','a')
f.close()
# Using biopython to fetch ids of the keyword searches
limit = 10
def fetch_ids(keyword,limit):
for item in keyword:
print item
print "Fetching search for "+item+"\n"
#os.environ['http_proxy'] = '127.0.0.1:13828'
Entrez.email = 'A.N.Other#example.com'
search = Entrez.esearch(db='pubmed',retmax=limit,term = '"'+item+'"')
print term
result = Entrez.read(search)
ids = result['IdList']
#print len(ids)
return ids
print fetch_ids(keyword_list,limit)
id_res = fetch_ids(keyword_list,limit)
print id_res
def write_ids_in_file(id_res):
with open(item+'.txt','w') as temp_file:
temp_file.write('\n'.join(ids))
temp_file.close()
write_ids_in_file(id_res)
In a nutshell what I'm trying to do is to create folders with the same name as each of the keywords, create a text file within the folder, fetch the ids from pubmed through the code and save the ids in the text files. My program worked fine when I initially tested it, however, after a couple of tries it started throwing me the target machine actively refused connection error. Some more details that could be useful,
header information
Host = 'eutils.ncbi.nlm.nih.gov'
Connection = 'close'
User-Agent = 'Python-urllib/2.7'
URL
http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?term=%22inflammasome%22&retmax=10&db=pubmed&tool=biopython&email=A.N.Other%40example.com
host = '127.0.0.1:13828'
I know that this question has been asked many times with the response that the port is not listening but what I want to know is if this is my issue as well, then how do get the application to work on this specific port. I've already gone to my firewall settings and opened a port 13828 but I'm not sure what to do beyond this. If this is not the case, what could potentially be a work around solution?
Thanks!
You need search.close() after result = Entrez.read(search). Check official instruction here. http://biopython.org/DIST/docs/api/Bio.Entrez-module.html
Shut down port or TCP due to too many open connections is a normal behavior for a public website.
I have one window active directory and I have connected my computer to active directory for accessing the computers which is connected.
I have written below python code For connecting,
import wmi
try:
connection = wmi.WMI(ip, user=username, password=password)
print "connection is establised"
for users in connection.Win32_SystemUsers():
print users
except:
print "connection failed"
Above code is showing all users list but i don't know how to get computers list with wmi win32 class.
Now problem is I want computer list which is in active directory using python. Anyone help me.
or
I found another method for connecting, that is ldap but here same problem is occuring. i am not able to find or access computer list.
I have used below code for connecting and showing user list
l = ldap.initialize("ldap://192.168.1.40")
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s("administrator#example.com", "example#123")
base = "dc=example, dc=com"
criteria = "(&(objectClass=user)(sAMAccountName=*))"
attributes = ['displayName', 'company']
result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria, attributes)
results = [entry for dn, entry in result if isinstance(entry, dict)]
print results
finally:
l.unbind()
Now how to get computer's list
Thanks in advance!
If you want to search for computer why do you search for users?
criteria = "(&(objectClass=user)(sAMAccountName=*))"
Try this:
criteria = "(&(objectClass=computer))"
I am having problems using the pyUSB library to read data from an ELM327 OBDII to USB device. I know that I need to write a command to the device on the write endpoint and read the received data back on the read endpoint. It doesn't seem to want to work for me though.
I wrote my own class obdusb for this:
import usb.core
class obdusb:
def __init__(self,_vend,_prod):
'''Handle to USB device'''
self.idVendor = _vend
self.idProduct = _prod
self._dev = usb.core.find(idVendor=_vend, idProduct=_prod)
return None
def GetDevice(self):
'''Must be called after constructor'''
return self._dev
def SetupEndpoint(self):
'''Must be called after constructor'''
try:
self._dev.set_configuration()
except usb.core.USBError as e:
sys.exit("Could not set configuration")
self._endpointWrite = self._dev[0][(0,0)][1]
self._endpointRead = self._dev[0][(0,0)][0]
#Resetting device and setting vehicle protocol (Auto)
#20ms is required as a delay between each written command
#ATZ resets device
self._dev.write(self._endpointWrite.bEndpointAddress,'ATZ',0)
sleep(0.002)
#ATSP 0 should set vehicle protocol automatically
self._dev.write(self._endpointWrite.bEndpointAddress,'ATSP 0',0)
sleep(0.02)
return self._endpointRead
def GetData(self,strCommand):
data = []
self._dev.write(self._endpintWrite.bEndpointAddress,strCommand,0)
sleep(0.002)
data = self._dev.read(self._endpointRead.bEndpointAddress, self._endpointRead.wMaxPacketSize)
return data
So I then use this class and call the GetData method using this code:
import obdusb
#Setting up library,device and endpoint
lib = obdusb.obdusb(0x0403,0x6001)
myDev = lib.GetDevice()
endp = lib.SetupEndpoint()
#Testing GetData function with random OBD command
#0902 is VIN number of vehicle being requested
dataArr = lib.GetData('0902')
PrintResults(dataArr)
raw_input("Press any key")
def PrintResults(arr):
size = len(arr)
print "Data currently in buffer:"
for i in range(0,size):
print "[" + str(i) + "]: " + str(make[i])
This only ever prints the numbers 1 and 60 from [0] and [1] element in the array. No other data has been return from the command. This is the case whether the device is connected to a car or not. I don't know what these 2 pieces of information are. I am expecting it to return a string of hexadecimal numbers. Does anyone know what I am doing wrong here?
If you don't use ATST or ATAT, you have to expect a timeout of 200ms at start, between every write/read combination.
Are you sending a '\r' after each command? It looks like you don't, so it's forever waiting for a Carriage Return.
And a hint: test with 010D or 010C or something. 09xx might be difficult what to expect.
UPDATE:
You can do that both ways. As long as you 'seperate' each command with a carriage return.
http://elmelectronics.com/ELM327/AT_Commands.pdf
http://elmelectronics.com/DSheets/ELM327DS.pdf (Expanded list).
That command list was quite usefull to me.
ATAT can be used to the adjust the timeout.
When you send 010D, the ELM chip will wait normally 200 ms, to get all possible reactions. Sometimes you can get more returns, so it waits the 200 ms.
What you also can do, and it's a mystery as only scantools tend to implement this:
'010D1/r'
The 1 after the command, specifies the ELM should report back, when it has 1 reply from the bus. So it reduces the delay quite efficiently, at the cost of not able to get more values from the address '010D'. (Which is speed!)
Sorry for my english, I hope send you in the right direction.