I am trying to come up with a script to check if a domain name resolves to its IP address via dns; using a python script I wrote.
I want to be able to do this in a few sequential loops, however after trying to run a loop once, the second time i run the script, the names that previously returned a successful dns resolution response, now do not.
Below is my script:
#! C:\Python27
import socket,time
localtime = time.asctime( time.localtime(time.time()) )
def hostres(hostname):
print "Attempting to resolve " + hostname
try:
socket.gethostbyname(hostname)
print "Resolved Successfully!"
except socket.error:
print "Could Not Resolve"
print "*************************************************"
print "Website loop starting.."
print "Local current time :", localtime
print "*************************************************"
print ""
text_file = open("sites.txt", "r")
lines = text_file.readlines()
for line in lines:
hostres(line)
text_file.close()
The contents of the text file are:
www.google.com
en.wikipedia.org
www.youtube.com
us.gamespot.com
I am thinking it is to do with these domains servers recognizing the script as a "bot" rather than a legitimate end-user, would it be correct to assume this?
If so, how can I still check if the dns name resolves by looking up the name of the website (or IP, does not matter) and be able to run this without getting a false reading of "request failed" despite the fact that the service is fully accessible from a browser?
Several problems in this question.
You are not checking if "a website responds" you are testing DNS resolution. All your DNS requests go to a single name server, your LDNS resolver. If all of them resolve, it still says nothing about the status of the website. Also, since you aren't actually talking to these website, they have no way of knowing you're a bot. They can only detect this (based on the HTTP user-agent header) if you make a HTTP request.
Regarding your code problem, you need to trim the newline character before you can do a socket.gethostbyname() on it. Replace socket.gethostbyname(hostname) with socket.gethostbyname(hostname.rstrip()) and you'll be fine.
Related
I have a server list:
hosts=['server1','server2','server3','server4']
there are server 4 monitoring tools accessed by api calls. these monitoring env urls basically the same except for each env has unique id which is part of the url. These servers can be on any of the 4 monitoring tools. I need to find out which url these servers belong to.
for example, these are the monitoring tools urls:
production_env="https://example.com/e/envid123"
dev_env="https://example.com/e/envid678"
test_env="https://example.com/e/envid567"
uat_env="https://example.com/e/envid1000"
given the server name, I need to find out which env they belong to.
given a server name, for example "server1",
api url would become https://example.com/e/envid123&serverName="server1", this url will give whether server1 exists in production_env or not. I need to check each env url until I find the given server.
I am trying something like this:
envId=['envid123','envid678','envid567','envid1000']
for server in hosts:
for id in envId:
url="https://example.com/e/"+id+&serverName=server
resp=request.get(url)
Any ideas how could do this the best way?
You need quotes around &serverName= to concatenate them. But it's simpler to use a formatting method, such as f-strings.
To find the desired URL, use resp.json to get the decoded JSON, and check the value of the appropriate dictionary element.
found = False
for server in hosts:
for id in envId:
url = f"https://example.com/e/{id}&serverName={server}"
resp = request.get(url)
if resp.json['totalCount'] > 0:
found = True
print(f"Success at host = {server} id = {id}")
break
if found:
break
else:
print("No server found")
I have huge problem with OPCDA and OpenOPC. I should (must) read a set of tags from a remote server, I have no access to the machine in any way. I only know the IP and the OPC server name.
Testing OpenOPC locally with this code all work fine. Otherwise, changing the hostname with the remote one nothing work with 0x800706BA error.
import OpenOPC
import time
try:
opc = OpenOPC.client()
opc.servers()
#change localhost to remote
opc.connect('Matrikon.OPC.Simulation.1', 'localhost')
srvList = opc.list()
print(srvList)
tags = opc.read(opc.list('Simulation Items.Random.Int*'), group='myTest')
for name, value, quality, tagTime in opc.read(opc.list('Simulation Items.Random.Int*'), group='myTest'):
print(name, value, quality, tagTime)
for tag in tags:
print(tag)
except Exception as e:
print('OPC failed')
print(str(e))
pass
finally:
print('END')
Anyone have any ideas on this?
Not having access to the server (set with anonymous logon), I have done DCOM configurations as much as possible.
Does anyone know a procedure for a possible solution?
Thanks!
I'm currently trying to send a HTTP POST via requests library in Python to a remote server to validate a serial number. I've already accomplished this with the following script:
validate-request.py
#!/usr/bin/env python
import requests
print "Content-type: text/html\r\n"
print "\r\n"
r = requests.post("https://xx.xx.xx.xx/cgi-bin/verify.py", data={'serial':'XXXXXXX')}, verify=True)
This already works great. When the serial number is validated, I would really like it to respond by offering a download and/or possibly text accompanied with it. I'm currently only able to validate the serial (the actual script is much longer as it fetches it from MySQL, so this is a simpler version.)
validate.py
#!/usr/bin/python
import cgi
form = cgi.FieldStorage()
serial = form.getvalue('serial')
print "Content-type:text/html\r\n\r\n"
print "<b>SERIAL OK</b></br>"
if serial == "XXXXXXX":
print "Content-type:text/html\r\n\r\n"
print "SERIAL <b>OK</b></br>"
else:
print "Content-type:text/html\r\n\r\n"
print "SERIAL <b>NOT OK</b></br>"
What I would also like to include is returning some extra information (text, mainly) and possibly offering a file to download.
This means, on the validate-request.py, I would have to play with the r.text it returns. Is there perhaps a way to scan the return text to find what I'm looking for? Also, how would I go about offering the file from validate.py and how would I go about accepting it from validate-request.py?
I'm trying to implement an authentication section into the smbserver.py from the impacket lib.
I changed the errorCode at the Line 2201 to STATUS_LOGON_FAILURE under some conditions, but my windows client keeps requesting with the same credentials like 10 times before he asks the user to enter new credentials. When I submit the windows dialog the credentials dont get sent to the script.
Heres my code section:
if not authenticateMessage['user_name'] == "testUser":
print "username not valid"
errorCode = STATUS_LOGON_FAILURE
respToken['NegResult'] = '\x02'
else:
print "logged in" + authenticateMessage['user_name']
errorCode = STATUS_SUCCESS
respToken['NegResult'] = '\x00'
Did somebody write a working authentication section there? Thanks!
The link you have provided is not the official repository for the library. Use https://github.com/CoreSecurity/impacket in the future.
The code you specified is almost right except the fact that the user_name field inside the authenticateMessage is Unicode encoded.
You can see the contents of the authenticateMessage structure by calling its dump() method (authenticateMessage.dump()).
I've replaced your code with:
authenticateMessage.dump()
respToken = SPNEGO_NegTokenResp()
if authenticateMessage['user_name'].decode('utf-16le') == "testUser":
errorCode = STATUS_SUCCESS
respToken['NegResult'] = '\x00'
else:
errorCode = STATUS_LOGON_FAILURE
respToken['NegResult'] = '\x02'
If you cloned master (https://github.com/CoreSecurity/impacket) you will see a new example called examples/smbserver.py (don't get confused with the impacket/smbserver.py library) which makes it easier to launch a simple server. Just run:
smbserver.py shareName sharePath
(e.g. smbserver.py TMP /tmp)
I made the aforementioned changes and ran the smbserver.py example and then, from a windows 7 cmd.exe prompt I ran (assuming the SMB server runs at 172.16.123.1 and the logged in username is not testUser):
start \\172.16.123.1
If you sniff the traffic you will see three attempts to login unsuccessfully and then Windows Explorer will popup a dialog box asking for new credentials. If you specify testUser as username (password can be anything) you will end up connecting to the target SMB server.
Like the title says, my code basically does this:
set proxy, test proxy, do some cool stuff
But after the proxy is set the first time, it sticks that way, never changing. This is the failing code:
# Pick proxy
r = random.randint(0, len(proxies) - 1)
proxy = proxies[r]
print proxy
# Setup proxy
l_proxy_support = urllib2.ProxyHandler({"http": "http://{0}:{1}".format(*proxy)})
l_opener = urllib2.build_opener(l_proxy_support)
try:
l_req = l_opener.open(
urllib2.Request('http://[MYIPADDRESSHERE]/ip.php', None, agent)
)
print l_req.read()
except urllib2.URLError:
print "Proxy not functioning, aborting..."
# Do cool stuff here, not really relevant
The output ends up being:
['X.Y.Z.124', '666', 'http']
[Skarlet] Your IP address is: X.Y.Z.124
['X2.Y2.Z2.190', '666', 'http']
[Skarlet] Your IP address is: X.Y.Z.124
['X3.Y3.Z3.41', '666', 'http']
[Skarlet] Your IP address is: X.Y.Z.124
I'm really puzzled right now.
Thanks for your time.
PD: the script that responds from my home IP address is just a PHP echoing $_SERVER['REMOTE_ADDR'].
That does seem strange. I've always found the httplib2 module to be the easiest Python HTTP client to work with. There is an example of using httplib2 with the socks module.
Sorry, I know this isn't a specific answer to your question, but it might be a workaround to try.