How to Stop python Programm if a certain URL is reachable - python

Can anybody help me with this small dilemma? I want to stop the python programm if the IP address 10.10.10.2 is reachable WITHIN 10 SECONDS. if it is not reachable in 10 SECONDS it should handle the exception and continue with the programm. if 10.10.10.2 is reachable then it should print "This IP address is reachable you are using the wrong device please disconnect" i thought about putting a ´´´sys.exit(1)´´´ after the except but im constantly getting errors. I am very new to python or any programming language for that matter so any example snippet codes and help are much appreciated
import pandas as pd
from xml.dom import minidom
import urllib.request
import time
from urllib.error import HTTPError
print(100*"#")
try:
preflash = urllib.request.urlopen("http://10.10.10.2", timeout=10).getcode()
print("Web page status code:", preflash)
print("IP address: 10.10.10.2 is reachable")
except urllib.error.URLError:
correct = urllib.request.urlopen("http://192.168.100.5", timeout=10).getcode()
print("Web page status code:", correct)
print("IP address: 192.168.100.5 is reachable")
print(100*"#")
# Declare url String
url_str = 'http://192.168.100.2/globals.xml'
# open webpage and read values
xml_str = urllib.request.urlopen(url_str).read()
# Parses XML doc to String for Terminal output
xmldoc = minidom.parseString(xml_str)
# Finding the neccassary Set points/ Sollwerte from the xmldoc
time.sleep(0.5)
# prints the order_number from the xmldoc
order_number = xmldoc.getElementsByTagName('order_number')
print("The Order number of the current device is:", order_number[0].firstChild.nodeValue)
print(100*"-")
The output of the python programm looks like this:
Web page status code: 200
IP address: 10.10.10.2 is reachable the programm will shut down in 5 seconds
####################################################################################################
The Order number of the current device is: 58184
----------------------------------------------------------------------------------------------------
The programm needs to shut down if 10.10.10.2 is reachable

Quite Stupid of me, all i needed to do was to add sys.exit(1) function before the except.
try:
preflash = urllib.request.urlopen("http://10.10.10.2", timeout=10).getcode()
print("Web page status code:", preflash)
print("IP address: 10.10.10.2 is reachable")
sys.exit(1)
except urllib.error.URLError:
correct = urllib.request.urlopen("http://192.168.100.5", timeout=10).getcode()
print("Web page status code:", correct)
print("IP address: 192.168.100.5 is reachable")

Related

How can i get http requests in python 3 and have the program sort the status codes

I have a list of cidr notations and i have a python program that generates a list of ip adress from the cidr notation.Here is the program
from netaddr import IPNetwork
for ip in IPNetwork('104.24.0.0/6'):
print ('%s' % ip)
But i want to make the program loop through each of the ip adress and send http requests then search for some specific status code and if it finds the required status code it should return which ip adress has that status code
Try this:
import requests
from netaddr import IPNetwork
required_status_code = 200 # your required status code goes here
for ip in IPNetwork('104.24.0.0/6'):
resp = requests.get(f'http://{ip}')
if resp.status_code == requires_status_code:
print (f'ip {ip} matches required status code!')

How to parallelly run code blocks in python

I am working on testing mass number of devices hence I am writing a testing program so i could automate the task.
Please bare with me because I am new to Python or any Programming language.
i want to be able to run the try and except code blocks parallely so that I dont have to wait 10 seconds for every new device that gets checked(picture over 1000 devices).
so basically:
try:
preflash = urllib.request.urlopen("http://10.10.10.2", timeout=10).getcode()
print("Web page status code:", preflash)
print("FAIL")
sys.exit(0)
except urllib.error.URLError:
correct = urllib.request.urlopen("http://192.168.100.5", timeout=10).getcode()
print("Web page status code:", correct)
print("IP address: 192.168.100.5 is reachable")
this code block should run parallely. if 10.10.10.2 is first reachable then it shuts down but if 192.168.100.5 is reachable before it then it should continue with the programm.
here is what the output looks like just for your reference.
Any help is much appreciated and please go easy on me guys cheers!
print(100*"#")
try:
preflash = urllib.request.urlopen("http://10.10.10.2", timeout=10).getcode()
print("Web page status code:", preflash)
print("FAIL")
sys.exit(0)
except urllib.error.URLError:
correct = urllib.request.urlopen("http://192.168.100.5", timeout=10).getcode()
print("Web page status code:", correct)
print("IP address: 192.168.100.5 is reachable")
print(100*"#")
print("Fetching device variables")
time.sleep(3)
print(100*"-")
# Declare url String
url_str = 'http://192.168.100.2/globals.xml'
# open webpage and read values
xml_str = urllib.request.urlopen(url_str).read()
# Parses XML doc to String for Terminal output
xmldoc = minidom.parseString(xml_str)
# Finding the neccassary Set points/ Sollwerte from the xmldoc
time.sleep(0.5)
# prints the order_number from the xmldoc
order_number = xmldoc.getElementsByTagName('order_number')
odr_nmr = order_number[0].firstChild.nodeValue
print("The Order number of the current device is:", odr_nmr)
print(100*"-")

Ip address checker doesn't output IP address

Following the code from here I have got an IP address checker. However instead of outputting an IP address it outputs []. Code:
import urllib.request
import re
print("we will try to open this url, in order to get IP Address")
url = "http://checkip.dyndns.org"
print(url)
request = urllib.request.urlopen(url).read()
theIP = re.findall(r"d{1,3}.d{1,3}.d{1,3}.d{1,3}", request.decode('utf-8'))
print("your IP Address is: ", theIP)
Expected output:
we will try to open this url, in order to get IP Address
http://checkip.dyndns.org
your IP Address is: 40.74.89.185
The IP address there is not mine and comes from HERE.
Real output:
we will try to open this url, in order to get IP Address
http://checkip.dyndns.org
your IP Address is: []
I have just copied from the website and then fixed the errors. What have I done wrong. Help please...
My python version is idle 3.8.
Turns out that your regex where wrong:
I've updated the code and using requests get:
findall will return a list of elements since you are get only one ip back just use [0]
from requests import get
import re
iphtml = get('http://checkip.dyndns.org').text
theIP = re.findall( r'[0-9]+(?:\.[0-9]+){3}', iphtml)
print(f"Your IP is: {theIP[0]}")
Your code updated:
import urllib.request
import re
print("we will try to open this url, in order to get IP Address")
url = "http://checkip.dyndns.org"
print(url)
request = urllib.request.urlopen(url).read()
theIP = re.findall(r'[0-9]+(?:\.[0-9]+){3}', request.decode('utf-8'))
print("your IP Address is: ", theIP[0])

changing ip in iteration with tor python

I want to change my IP everytime I run through loop. I am trying to achieve it with TOR. I have seen few posts with similar question, but solution given there is not working. So far my code looks like:
import socks
#import socket
import requests
import time
for i in range(1,3):
socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_SOCKS5, addr="127.0.0.1", port=9050)
try:
print (requests.get("http://icanhazip.com").text)
except Exception as e:
time.sleep(30)
print (type(e))
print (e)
I need different IP every time, instead of same IP.
edit : I have tried using approach given on How to change Tor identity in Python?. My limitation is not to use any external libraries. also solution provided by Nedim is without external library.
so far I have tried following to get different IP from mentioned link:
import socket
import sys
import os
try:
tor_c = socket.create_connection(("127.0.0.1", 9051 ))
secret = os.urandom(32) # pass this to authenticate
hash = tor_c.s2k_gen(secret) # pass this to Tor on startup.
tor_c.send('AUTHENTICATE "{}"\r\nSIGNAL NEWNYM\r\n'.format(hash))
response = tor_c.recv(1024)
if response != '250 OK\r\n250 OK\r\n':
sys.stderr.write('Unexpected response from Tor control port: {}\n'.format(response))
except Exception as e:
sys.stderr.write('Error connecting to Tor control port: {}\n'.format(repr(e)))
but it is throwing following error:
Error connecting to Tor control port: ConnectionRefusedError(10061, 'No connection could be made because the target machine actively refused it', None, 10061, None)
def renew_connection():
with Controller.from_port(port=9051) as controller:
controller.authenticate(password='password')
controller.signal(Signal.NEWNYM)
controller.close()
def request_tor(url, headers):
print((requests.get(url,proxies={'http': 'socks5h://localhost:9050'}, headers=headers)).text)
r = requests.get(url)
print('direct IP:', r.text)
if __name__ == "__main__":
url = 'http://icanhazip.com'
headers = { 'User-Agent': UserAgent().random }
for i in range(5):
request_tor(url,headers)
renew_connection()
time.sleep(5)

what is the syntax for sending a socket GET request with user input

I am trying to prompt user for URL so it can read any page, but I keep getting the 400 bad request error when I run my program.
I have established a socket connection with the host from my input. But when I try sending a GET request, it blows up on me, with a 400 bad request error. What can I do please?
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
url = raw_input('Enter - ')
splt = url.split('/')
mysock.connect((splt[2], 80))
mysock.send('GET url \n\n')
except:
print 'invalid URL'
while True:
data = mysock.recv(512)
if (len(data) < 1 ):
break
print data
mysock.close()
It looks to me like you aren't calling the GET properly. When you write
mysock.send('GET url \n\n')
You aren't embedding the variable "url" into the command but simply a string with the phrase "url".
I don't know, but that could be worth checking.
My own code looks like this:
cmd = 'GET '+address+' HTTP/1.0\r\n\r\n'
cmd = cmd.encode()
mysock.send(cmd)
Where "address" is the name of the address entered by the user.

Categories