Loop in Django Model - django

I have a IP Block calculator web application that will print a range of IP addresses based on slashes. However it only saves the last record in the range into the text field. I want to be able to save it all to the text field.
I am using python-ipy with my code. Look at the last for loop "rangeip",
Here is my code:
#ip block and range save function
def save(obj, *args, **kwargs):
subnet = unicode(obj.subnet)
first = IP(obj.ip_start + subnet).net()
broadcast = IP(obj.ip_start + subnet).broadcast()
print first
print broadcast
obj.broadcast_ip = broadcast
ip_block = IP(obj.ip_start + subnet)
ip_block.WantPrefixLen = 3
ip = IP(obj.ip_start + subnet)
for gateway in ip[1]:
obj.gateway_ip = gateway
print gateway
#rangeip for loop
for rangeip in ip:
obj.ip_range = rangeip
print rangeip
super(IP_block, obj).save(*args, **kwargs)
This is what I would like, to be able to save the list into a text field, it only saves the last ip: 192.168.1.31
Example I would like:
192.168.1.1
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.10
192.168.1.11
192.168.1.12
192.168.1.13
192.168.1.14
192.168.1.15
192.168.1.16
192.168.1.17
192.168.1.18
192.168.1.19
192.168.1.20
192.168.1.21
192.168.1.22
192.168.1.23
192.168.1.24
192.168.1.25
192.168.1.26
192.168.1.27
192.168.1.28
192.168.1.29
192.168.1.30
192.168.1.31
Any help is greatly appreciate it.

obj.ip_range = rangeip is an assignment. You are replacing the content of obj.ip_range with the new rangeip.
What you need to do is:
obj.ip_range += "%s"%rangeip

Related

"requests-html" proxy setting not working

I'm using the following code to set the proxy for the HTMLSession, get() method. Still, it uses my IP instead of the proxy IP.
proxy string format:
http://username:password#ip:port
r = session.get('https://whatismyipaddress.com/', proxies={'http': proxy})
r.html.find('p.ip-address')[0].text
above print the following which is my current IP address.
'IPv4:? The most common IP version is assigned by ISPs. 175.157.?.?'
You need to add 'https' in proxies:
proxy = 'http://username:password#ip:port'
r = session.get('https://whatismyipaddress.com/', proxies={'http': proxy, 'https': proxy})

Have to find IP address OR IP address pattern in string

I have a below and many more below like strings in list.. I have to extract the IP addresses only from each string.
"Below server have been decommissioned via # C180013538 & C180025327 request.
Please remove any firewall rules associated with this server, So that the IP\'s can be re-used in the future.
Please refer attachment for FW rules removal server details.", \'Server Details :- \', \'ServerName IP Address\', \'CHIIUGA06RR
10.103.225.37\', \'CICCKDBP11VE 10.103.113.11\', \'CICCKDBP12VE 10.103.113.13\
/"
Expected Result : -
10.103.225.37
10.103.113.11
10.103.113.13
import re
list = ["\'Server Details :- \', \'ServerName IP Address\', \'CHIIUGA06RR 10.103.225.37\', \'CICCKDBP11VE 10.103.113.11\', \'CICCKDBP12VE 10.103.113.13\ /",
"\'Server Details :- \', \'ServerName IP Address\', \'CHIIUGA06RR 10.103.225.37\', \'CICCKDBP11VE 10.103.113.11\', \'CICCKDBP12VE 10.103.113.13\ /"]
for s in list:
print re.findall( r'[0-9]+(?:\.[0-9]+){3}', s)
See: Extract IP address from an html string (python)

Add PTR record using dnspython

Im trying to add a PTR record with dnspython to bind9 using this code:
def send_query(query, server):
update = dns.query
update.tcp(query, server)
def add(name, rdtype, rdata, ttl=300, zone):
server = dns.resolver.Resolver()
server.nameservers = '<dns server>'
keyring = dns.tsigkeyring.from_text({
'key-name': 'key'
})
record = dns.update.Update(zone=zone, keyring=keyring)
record.add(name, ttl, rdtype, rdata)
send_query(record, server.nameservers)
Im able to successfully add the record when passing:
name = last octet
rdtype = PTR
data = server-FQDN
zone = z.y.x.in-addr.arpa
but when querying the dns server via nslookup I get:
~ nslookup X.Y.Z.6
Server: NS server
Address: NS server#53
6.Z.Y.X.in-addr.arpa name = server-FQDN.Z.Y.X.in-addr.arpa.
The problem is the "Z.Y.X.in-addr.arpa." part added to the query.
In the zone file the record is in the right syntax
Is there a better way to add PTR record with dnspython?
The reason this didn't work was that I forgot to add the ending "." at the end of the hostname FDQN and therefore the domain was completed automatically.

Q: Converting hostname to IP from a dictionary for netmiko connection?

In the past, I was able to do something simple like this to read a file
of IP addresses that I would iterate through to SSH to each one
# Grab the list of devices from a text file
devices = open('./devices.txt','r').read().split('\n')
# Connect to each router and do a show run command
for device in devices:
net_connect = ConnectHandler(device_type="cisco_ios", ip=device, username="myusername",
password=password)
This time, however, I need to do something a bit more complex.
I pull some data from a JSON source where I can derive a "hostname."
But I cannot connect to the "hostname." If the hostnames were in DNS
that would be easier but sadly they are not.
So.. I have a list of hosts to IPs that I figured I could use and pull
into a dictionary.
But now I somehow need to match up the hostname that gets derived from
the JSON data to match against a switchname in the hosts.csv so that I can
then basically convert hostname to IP so that I can then iterate through each
device in devices to SSH into each one.
This is all I have so far. I'm stuck at this point. Not sure how to match
things up to get the IP to use in my net_connect statement.
# Creat dict mapping hostnames to IP address for devices
with open(r'hosts.csv', 'r') as f:
for line in f:
switch = {}
switch_line = line.split(',')
switch = {
'ip': switch_line[1],
'switchname': str(switch_line[0]).strip('\n')
# Define list of devices to connect to and the config changes to be made
pa = []
# This data is coming from a JSON source
for device in devices:
if device['switchParent']:
hostname = device['switchParent']
else:
hostname = device['destDevice']
# hostname technically is the device I need to connect
# however it needs to resolve to an IP from the switch dict earlier
net_connect = ConnectHandler(device_type="cisco_ios", ip=hostname,
username="myusername", password=password)
Assuming that switchname has a unique ip address then you should parse the hosts.csv file this way:
# Create dict mapping hostnames to IP address for devices
switch = {}
with open(r'hosts.csv', 'r') as f:
for line in f:
switch_line = line.split(',')
switch[str(switch_line[0].strip())] = switch_line[1]
Then you go through the JSON data source:
# This data is coming from a JSON source
for device in devices:
if device['switchParent']:
hostname = device['switchParent']
else:
hostname = device['destDevice']
# hostname technically is the device I need to connect
# however it needs to resolve to an IP from the switch dict earlier
net_connect = ConnectHandler(device_type="cisco_ios", ip=switch[hostname],
username="myusername", password=password)
That should work IF hostname is expected to be one of the keys from the switch dict.

GeoIP always shows the server's IP address

I am trying to use GeoIP, but I have a problem when I use REMOTE_ADDR. The IP shown is that of my server and not the client.
from django.contrib.gis.geoip import GeoIP
Example context:
g = GeoIP()
ip = self.request.META.get('REMOTE_ADDR')
context['my_ip'] = ip # this display ip client
context['pais_anuncio'] = g.country_code('ip') # this display ip my server.
What am I doing wrong, Thank you.
My guess is, since you are passing the string 'ip', it is defaulting to your server's IP. Try passing in the variable ip, like this:
context['pais_anuncio'] = g.country_code(ip)