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
Related
Here's what I'm doing:
from urllib import quote_plus
email = quote_plus('name+other#gmail.com')
but
print email
> name+other%40gmail.com
so if I put it in a URL the + becomes a space when I pull it out. But I want it to stay a plus. What am I doing wrong?
Try to define safe parameter explicitly, like in the code below:
from urllib import quote_plus
email = quote_plus('name+other#gmail.com', safe='/')
print email
If that works the reason I can assume is that the source code of the urllib.quote_plus has been modified somehow...
Does anyone know of a Python module or a solution for how I could lookup company info (Name preferably) via the ASN (autonomous system number) number?
There are lots of IP to ASN tools but that is not what I require.
ASN needs to be the input - company name output.
This website has the sort of info I need:
http://bgp.potaroo.net/cgi-bin/as-report?as=AS5607&view=2.0
Any ideas are appreciated!
Try this, it's maybe what you need
from cymruwhois import Client
import ipresolved
domain='facebook.com'
ips=ipresolved.getipresolvedfromdomain(domain)
c=Client()
for i in ips.json()['resolutions']:
ip=i['ip_address']
print('ip : '+ip)
r=c.lookup(ip)
print('asn number: ',r.asn)
print('asn owener : ',r.owner)
print('==============')
That information is available publicly on the CIDR-Report website.
This url has all the info you need and is updated daily. Big file, it might take a while to load :
http://www.cidr-report.org/as2.0/autnums.html
A slightly updated version of #Al-Pha answer:
Multi lookup:
from cymruwhois import Client
import socket
c = Client()
ip = socket.gethostbyname('globalresearch.ca')
for r in c.lookupmany([ip, "213.73.91.35"]):
print(r.__dict__)
# print(r.asn)
Single lookup:
c = Client()
r = c.lookup("213.73.91.35")
print(r.asn)
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.
How can I grab a picture off of a known url and save it to my computer using Python (v2.6)? Thanks
You can use urllib.urlretrieve.
Copy a network object denoted by a URL to a local file, if necessary.
Example:
>>> import urllib
>>> urllib.urlretrieve('http://i.imgur.com/Ph4Xw.jpg', 'duck.jpg')
('duck.jpg', <httplib.HTTPMessage instance at 0x10118e830>)
# by now the file should be downloaded to 'duck.jpg'
You can use urllib.urlretrieve:
import urllib
urllib.urlretrieve('http://example.com/file.png', './file.png')
If you need more flexibility, use urllib2.
In the absence of any context, the following is a simple example of using standard library modules to make an non-authenticated HTTP GET request
import urllib2
response = urllib2.urlopen('http://lolcat.com/images/lolcats/1674.jpg')
with open('lolcat.jpg', 'wb') as outfile:
outfile.write(response.read())
EDIT: urlretrieve() is new to me. I guess then you could turn it into a command line one-liner... if you're bored.
$ python -c "import urllib; urllib.urlretrieve('http://lolcat.com/images/lolcats/1674.jpg', filename='/tmp/1674.jpg')"
batteries are included in urllib:
urllib.urlretrieve(yourUrl, fileName)
import urllib2
open("fish.jpg", "w").write(urllib2.urlopen("http://www.fiskeri.no/Fiskeslag/Fjesing.jpg").read())
Easy.
import urllib
urllib.urlretrieve("http://www.dokuwiki.org/_media/wiki:dokuwiki-128.png","dafile.png")
I need to perform http PUT operations from python Which libraries have been proven to support this? More specifically I need to perform PUT on keypairs, not file upload.
I have been trying to work with the restful_lib.py, but I get invalid results from the API that I am testing. (I know the results are invalid because I can fire off the same request with curl from the command line and it works.)
After attending Pycon 2011 I came away with the impression that pycurl might be my solution, so I have been trying to implement that. I have two issues here. First, pycurl renames "PUT" as "UPLOAD" which seems to imply that it is focused on file uploads rather than key pairs. Second when I try to use it I never seem to get a return from the .perform() step.
Here is my current code:
import pycurl
import urllib
url='https://xxxxxx.com/xxx-rest'
UAM=pycurl.Curl()
def on_receive(data):
print data
arglist= [\
('username', 'testEmailAdd#test.com'),\
('email', 'testEmailAdd#test.com'),\
('username','testUserName'),\
('givenName','testFirstName'),\
('surname','testLastName')]
encodedarg=urllib.urlencode(arglist)
path2= url+"/user/"+"99b47002-56e5-4fe2-9802-9a760c9fb966"
UAM.setopt(pycurl.URL, path2)
UAM.setopt(pycurl.POSTFIELDS, encodedarg)
UAM.setopt(pycurl.SSL_VERIFYPEER, 0)
UAM.setopt(pycurl.UPLOAD, 1) #Set to "PUT"
UAM.setopt(pycurl.CONNECTTIMEOUT, 1)
UAM.setopt(pycurl.TIMEOUT, 2)
UAM.setopt(pycurl.WRITEFUNCTION, on_receive)
print "about to perform"
print UAM.perform()
httplib should manage.
http://docs.python.org/library/httplib.html
There's an example on this page http://effbot.org/librarybook/httplib.htm
urllib and urllib2 are also suggested.
Thank you all for your assistance. I think I have found an answer.
My code now looks like this:
import urllib
import httplib
import lxml
from lxml import etree
url='xxxx.com'
UAM=httplib.HTTPSConnection(url)
arglist= [\
('username', 'testEmailAdd#test.com'),\
('email', 'testEmailAdd#test.com'),\
('username','testUserName'),\
('givenName','testFirstName'),\
('surname','testLastName')\
]
encodedarg=urllib.urlencode(arglist)
uuid="99b47002-56e5-4fe2-9802-9a760c9fb966"
path= "/uam-rest/user/"+uuid
UAM.putrequest("PUT", path)
UAM.putheader('content-type','application/x-www-form-urlencoded')
UAM.putheader('accepts','application/com.internap.ca.uam.ama-v1+xml')
UAM.putheader("Content-Length", str(len(encodedarg)))
UAM.endheaders()
UAM.send(encodedarg)
response = UAM.getresponse()
html = etree.HTML(response.read())
result = etree.tostring(html, pretty_print=True, method="html")
print result
Updated: Now I am getting valid responses. This seems to be my solution. (The pretty print at the end isn't working, but I don't really care, that is just there while I am building the function.)