I'm using python ipaddr it's working but if I wanna open a text file where i'm getting an ip address i'm getting an error.
This is What I have:
import ipaddr
from itertools import islice
def address1():
with open('address.txt','r+') as file:
lines = islice(file, 1, 5)
for line in lines:
found_address = line.find('Address')
if found_address != -1:
address = line[found_address+len('Address:'):] #address = 192.168.0.9/25
mask = ipaddr.IPv4Network(address)
resultado = mask.broadcast
print resultado
return resultado
def get_network():
addr = '192.168.0.9/25'
mask = ipaddr.IPv4Network(addr)
resultado_broadcast = mask.broadcast
print resultado_broadcast
return resultado_broadcast
#address1() #if I comment out this line and I run the next one works...
get_network() #if I run this one works...
My ip address from address.txt :
Address 192.168.0.9/25
the same I used in get_network()
So why I'm getting error in address1()?
output of get_network()
As you can see works... but if I run address1()
I got this error.
Does anyone know how to make address1() work? is it possible?
thanks...!
Related
I am working on Stock predicting project.I want to download historical data from yahoo finance and save them in CSV format.
Since I am beginner in Python I am unable to correct the error.
My code is as follows:
import re
import urllib2
import calendar
import datetime
import getopt
import sys
import time
crumble_link = 'https://finance.yahoo.com/quote/{0}/history?p={0}'
crumble_regex = r'CrumbStore":{"crumb":"(.*?)"}'
cookie_regex = r'Set-Cookie: (.*?); '
quote_link = 'https://query1.finance.yahoo.com/v7/finance/download/{}?period1={}&period2={}&interval=1d&events=history&crumb={}'
def get_crumble_and_cookie(symbol):
link = crumble_link.format(symbol)
response = urllib2.urlopen(link)
match = re.search(cookie_regex, str(response.info()))
cookie_str = match.group(1)
text = response.read()
match = re.search(crumble_regex, text)
crumble_str = match.group(1)
return crumble_str, cookie_str
def download_quote(symbol, date_from, date_to):
time_stamp_from = calendar.timegm(datetime.datetime.strptime(date_from, "%Y-%m-%d").timetuple())
time_stamp_to = calendar.timegm(datetime.datetime.strptime(date_to, "%Y-%m-%d").timetuple())
attempts = 0
while attempts < 5:
crumble_str, cookie_str = get_crumble_and_cookie(symbol)
link = quote_link.format(symbol, time_stamp_from, time_stamp_to, crumble_str)
#print link
r = urllib2.Request(link, headers={'Cookie': cookie_str})
try:
response = urllib2.urlopen(r)
text = response.read()
print "{} downloaded".format(symbol)
return text
except urllib2.URLError:
print "{} failed at attempt # {}".format(symbol, attempts)
attempts += 1
time.sleep(2*attempts)
return ""
if __name__ == '__main__':
print get_crumble_and_cookie('KO')
from_arg = "from"
to_arg = "to"
symbol_arg = "symbol"
output_arg = "o"
opt_list = (from_arg+"=", to_arg+"=", symbol_arg+"=")
try:
options, args = getopt.getopt(sys.argv[1:],output_arg+":",opt_list)
except getopt.GetoptError as err:
print err
for opt, value in options:
if opt[2:] == from_arg:
from_val = value
elif opt[2:] == to_arg:
to_val = value
elif opt[2:] == symbol_arg:
symbol_val = value
elif opt[1:] == output_arg:
output_val = value
print "downloading {}".format(symbol_val)
text = download_quote(symbol_val, from_val, to_val)
with open(output_val, 'wb') as f:
f.write(text)
print "{} written to {}".format(symbol_val, output_val)
And the Error message that I am getting is :
File "C:/Users/Murali/PycharmProjects/generate/venv/tcl/generate2.py", line
49, in <module>
print get_crumble_and_cookie('KO')
File "C:/Users/Murali/PycharmProjects/generate/venv/tcl/generate2.py", line
19, in get_crumble_and_cookie
cookie_str = match.group(1)
AttributeError: 'NoneType' object has no attribute 'group'
So how can we resolve this problem that has popped up?
Look at these two commands:
match = re.search(cookie_regex, str(response.info()))
cookie_str = match.group(1)
The first one takes the string response.info() does a regular expression search to match cookie_regex. Then match.group(1) is supposed to take the match from it. The problem however is that if you do a print match in between these commands, you'll see that the re.search() returned nothing. This means match.group() has nothing to "group", which is why it errors out.
If you take a closer look at response.info() (you could just add a print response.info() command in your script to see it), you'll see that there's a line in response code that starts with "set-cookie:", the code after which you're trying to capture. However, you have your cookie_regex string set to look for a line with "Set-Cookie:". Note the capital letters. When I change that string to all lower-case, the error goes away:
cookie_regex = r'set-cookie: (.*?); '
I did run into another error after that, where print "downloading {}".format(symbol_val) stops because symbol_val hasn't been defined. It seems that this variable is only declared and assigned when opt[2:] == symbol_arg:. So you may want to rewrite that part to cover all cases.
I have been trying to do some basic search queries, but I am unable to connect to an open LDAP server regardless. I tried a couple of servers, and none of them worked. I used Apache Directory Studio to make sure that the keyword was there but it did not work either way. I tried a variety of different code from different sources.
This was the first one I used
:
https://www.linuxjournal.com/article/6988
import ldap
keyword = "boyle"
def main():
server = "ldap.forumsys.com"
username = "cn=read-only-admin,dc=example,dc=com"
password = "password"
try:
l = ldap.open(server)
l.simple_bind_s(username,password)
print "Bound to server . . . "
l.protocol_version = ldap.VERSION3
print "Searching . . ."
mysearch (l,keyword)
except ldap.LDAPError:
print "Couldnt connect"
def mysearch(l, keyword):
base = ""
scope = ldap.SCOPE_SUBTREE
filter = "cn=" + "*" + keyword + "*"
retrieve_attributes = None
count = 0
result_set = []
timeout = 0
try:
result_id = l.search(base, scope, filter, retrieve_attributes)
while l != 1:
result_id = l.search(base, scope,filter, retrieve_attributes)
result_type, result_data = l.result(result_id, timeout)
if result_data == []:
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
if len (result_set = 0):
print "No Results"
for i in range (len(result_set)):
for entry in result_set[i]:
try:
name = entry[1]['cn'][0]
mail = entry[1]['mail'][0]
#phone = entry[1]['telephonenumber'][0]
#desc = entry[1]['description'][0]
count = count + 1
print name + mail
except:
pass
except ldap.LDAPError, error_message:
print error_message
main()
Every time I ran this program, I received an error
{'desc': u"No such object"}
I also tried this
import ldap
try:
l = ldap.open("ldap.example.com")
except ldap.LDAPError, e:
print e
base_dn = "cn=read-only-admin,dc=example,dc=com"
search_scope = ldap.SCOPE_SUBTREE
retrieve_attributes = None
search_filter = "uid=myuid"
try:
l_search = l.search(base_dn, search_scope, search_filter, retrieve_attributes)
result_status, result_data = l.result(l_search, 0)
print result_data
except ldap.LDAPError, e:
print e
The error on this one was
{'desc': u"Can't contact LDAP server"}
I spent about 5 hours trying to figure this out. I would really appreciate it if you guys could give me some advice. Thanks.
There are several bogus things in there.
I will only comment your first code sample because it can be used by anyone with that public LDAP server.
l = ldap.open(server)
Function ldap.open() is deprecated since many years. You should use function ldap.initialize() with LDAP URI as argument instead like this:
l = ldap.initialize("ldap://ldap.forumsys.com")
l_search = l.search(..)
This is the asynchronous method which just returns a message ID (int) of the underlying OpenLDAP C API (libldap). It's needed if you want to retrieve extended controls returned by the LDAP server along with search results. Is that what you want?
As a beginner you probably want to use the simpler method LDAPObject.search_s() which immediately returns a list of (DN, entry) 2-tuples.
See also: python-ldap -- Sending LDAP requests
while l != 1
This does not make sense at all because l is your LDAPObject instance (LDAP connection object). Note that LDAPObject.search() would raise an exception if it gets an Integer error code from OpenLDAP's libldap. No need to do C-style error checks at this level.
filter = "cn=" + "" + keyword + ""
If keyword can be arbitrary input this is a prone to LDAP injection attacks. Don't do that.
For adding arbitrary input into a LDAP filter use function ldap.filter.escape_filter_chars() to properly escape special characters. Also avoid using variable name filter because it's the name of a built-in Python function and properly enclose the filter in parentheses.
Better example:
ldap_filter = "(cn=*%s*)" % (ldap.filter.escape_filter_chars(keyword))
base = ""
The correct search base you have to use is:
base = "dc=example,dc=com"
Otherwise ldap.NO_SUCH_OBJECT is raised.
So here's a complete example:
import pprint
import ldap
from ldap.filter import escape_filter_chars
BINDDN = "cn=read-only-admin,dc=example,dc=com"
BINDPW = "password"
KEYWORD = "boyle"
ldap_conn = ldap.initialize("ldap://ldap.forumsys.com")
ldap_conn.simple_bind_s(BINDDN, BINDPW)
ldap_filter = "(cn=*%s*)" % (ldap.filter.escape_filter_chars(KEYWORD))
ldap_results = ldap_conn.search_s(
"dc=example,dc=com",
ldap.SCOPE_SUBTREE,
ldap_filter,
)
pprint.pprint(ldap_results)
Using python I need to find the next IP address given a range of IP addresses I've already used. So if I have a list of IP address like...
IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5']
When I ask for the next IP address I need it to return '10.220.1.4'. The next request would return '10.220.1.6' and so on.
If you're using Python 3.3 (or newer), you can use the ipaddress module. Example for all hosts in the subnet 10.220.1.0/24 except for those in reserved:
from ipaddress import IPv4Network
network = IPv4Network('10.220.1.0/24')
reserved = {'10.220.1.1', '10.220.1.2', '10.220.1.3', '10.220.1.5'}
hosts_iterator = (host for host in network.hosts() if str(host) not in reserved)
# Using hosts_iterator:
print(next(hosts_iterator)) # prints 10.220.1.4
print(next(hosts_iterator)) # prints 10.220.1.6
print(next(hosts_iterator)) # prints 10.220.1.7
# Or you can iterate over hosts_iterator:
for host in hosts_iterator:
print(host)
So basically this can be done in a single line (+ imports and definition of network and reserved addresses).
If you're using Python 3 you could use ipaddress with generator:
import ipaddress
def gen_ip(start, reserved):
start = int(ipaddress.IPv4Address(start))
for i in range(start + 1, int(2 ** 32) + 1):
ip = str(ipaddress.IPv4Address(i))
if ip not in reserved:
yield ip
IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5']
j = 0
for ip in gen_ip(min(IPs), set(IPs)):
print(ip)
j += 1
if j == 5:
break
Output:
10.220.1.4
10.220.1.6
10.220.1.7
10.220.1.8
10.220.1.9
You can use an generator using the ipaddress module which is a bultin from python >= 3.3 or you can install with pip for earlier versions:
In [20]: from ipaddress import ip_network
In [21]: IPs = {'10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5'}
In [22]: net = ip_network(u"10.220.1.0/24")
In [23]: avail =(str(ip) for ip in net.hosts() if str(ip) not in IPs
....: )
In [24]: next(avail)
Out[24]: '10.220.1.4'
In [25]: next(avail)
Out[25]: '10.220.1.6'
Convert your list to a set, for performance:
used_ips = set(IPs)
Now generate your IP#'s however you would like, and check if they are contained in the set:
for next_ip in generate_ip_numbers():
if next_ip in used_ips:
continue
print("Next ip address is:", next_ip)
Create a basic ip object to hold a record of your current ip and to get the next ip
class IPObj(object):
def __init__(self, list_of_ips):
self.position = 0
self.ips = list_of_ips
self.current_ip = self.ips[self.position]
def next_ip(self, stop_iteration=False):
'''
return the next ip in the list
'''
if self.position >= len(self.ips)-1:
self.position = 0 # By default next_ip will do nothing when it reaches the end but it will throw an exception if stop_iteration==True
if stop_iteration:
raise StopIteration
self.position += 1
self.current_ip = self.ips[self.position]
return self.current_ip
def __repr__(self):
return repr(self.current_ip)
#Testing
ips = IPObj(['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5'])
print ips
while True:
print ips.next_ip(True),
Output:
10.220.1.1,
10.220.1.2,
10.220.1.3,
10.220.1.5,
Traceback (most recent call last):
File "C:\Users\J10ey\workspace\SO_Help\src\ip's.py", line 32, in
print ips.next_ip(True)
File "C:\Users\J10ey\workspace\SO_Help\src\ip's.py", line 21, in next_ip
raise StopIteration
StopIteration
I have project in internet security class. My partner started the project and wrote some python code and i have to continue from where he stopped. But i don't know python and i was planning to learn by running his code and checking how it works. however when i am executing his code i get an error which is "IndexError: list index out of range".
import os
# Deauthenticate devices
os.system("python2 ~/Downloads/de_auth.py -s 00:22:b0:07:58:d4 -d & sleep 30; kill $!")
# renew DHCP on linux "sudo dhclient -v -r & sudo dhclient -v"
# Capture DHCP Packet
os.system("tcpdump -lenx -s 1500 port bootps or port bootpc -v > dhcp.txt & sleep 20; kill $!")
# read packet txt file
DHCP_Packet = open("dhcp.txt", "r")
# Get info from txt file of saved packet
line1 = DHCP_Packet.readline()
line1 = line1.split()
sourceMAC = line1[1]
destMAC = line1[3]
TTL = line1[12]
length = line1[8]
#Parse packet
line = DHCP_Packet.readline()
while "0x0100" not in line:
line = DHCP_Packet.readline()
packet = line + DHCP_Packet.read()
packet = packet.replace("0x0100:", "")
packet = packet.replace("0x0110:", "")
packet = packet.replace("0x0120:", "")
packet = packet.replace("0x0130:", "")
packet = packet.replace("0x0140:", "")
packet = packet.replace("0x0150:", "")
packet = packet.replace("\n", "")
packet = packet.replace(" ", "")
packet = packet.replace(" ", "")
packet = packet.replace("000000000000000063825363", "")
# Locate option (55) = 0x0037
option = "0"
i=0
length = 0
while option != "37":
option = packet[i:i+2]
hex_length = packet[i+2:i+4]
length = int(packet[i+2:i+4], 16)
i = i+ length*2 + 4
i = i - int(hex_length, 16)*2
print "Option (55): " + packet[i:i+length*2 ] + "\nLength: " + str(length) + " Bytes"
print "Source MAC: " + sourceMAC
Thank you a lot
The index error probably means you have an empty or undefined section (index) in your lists. It's most likely in the loop condition at the bottom:
while option != "37":
option = packet[i:i+2]
hex_length = packet[i+2:i+4]
length = int(packet[i+2:i+4], 16)
i = i+ length*2 + 4
Alternatively, it could be earlier in reading your text file:
# Get info from txt file of saved packet
line1 = DHCP_Packet.readline()
line1 = line1.split()
sourceMAC = line1[1]
destMAC = line1[3]
TTL = line1[12]
length = line1[8]
Try actually opening the text file and make sure all the lines are referred to correctly.
If you're new to coding and not used to understanding error messages or using a debugger yet, one way to find the problem area is including print ('okay') between lines in the code, moving it down progressively until the line no longer prints.
I'm pretty new to python as well, but I find it easier to learn by writing your own code and googling what you want to achieve (especially when a partner leaves you code like that...). This website provides documentation on in-built commands (choose your version at the top): https://docs.python.org/3.4/contents.html,
and this website contains more in-depth tutorials for common functions: http://www.tutorialspoint.com/python/index.htm
I think the variable line1 that being split does not have as much as 13 numbers,so you will get error when executing statement TTL = line1[12].
Maybe you do not have the same environment as your partner worked with ,so the result you get(file dhcp.txt) by executing os.system("") maybe null(or with a bad format).
You should check the content of the file dhcp.txt or add statement print line1 after line1 = DHCP_Packet.readline() to check if it has a correct format.
I was trying to use the find and string slicing method to extract the number at the end of the line. but I get this mismatch error because I came back with position 18 but from what I have read and research this position is suppose to be 18 am I missing something here?
str = ('X-DSPAM-Confidence:0.8475')
atpos = str.find(':')
print atpos
sppos = str.find(' ',atpos)
print sppos
host = float(str[atpos + 1:sppos])
print host
str = ('X-DSPAM-Confidence:0.8475')
atpos = str.find(':')
sppos = str.find(' ',atpos)
host = float(str[atpos + 1:])
print (host)
You should rather use the string.split method than looking for the specific position of the : delimiter,
_str = 'X-DSPAM-Confidence:0.8475'
host = float(_str.split(':')[1])
print(host)
str = ('X-DSPAM-Confidence:0.8475')
atpos = str.find(':')
sppos = str.find(' ',atpos)
host = float(str[atpos + 1:])
print host
text = "X-DSPAM-Confidence: 0.8475";
spacePos = text.find(" ")
number = text[spacePos::1]
#not really necessary but since we are just learning and playing
strippedNumber = number.lstrip();
result = float(strippedNumber)
def reprint(printed):
print printed
reprint(result)