I am attempting to lookup whois information programmatically utilizing python3 and the whois command on Ubuntu.
For example:
import os
# Set domain
hostname = "google.com"
# Query whois
response = os.system("whois " + hostname)
# Check the response
print("This is the Response:" + str(response))
Returns this:
...MarkMonitor Domain Management(TM) Protecting companies and consumers in a digital world.
Visit MarkMonitor at https://www.markmonitor.com Contact us at +1.8007459229 In Europe, at +44.02032062220 -- **This is the Response:**0
Process finished with exit code 0
The whois information is presented as expected (not seen in quote), however, the response is always just the exit code.
I require the information that precedes the exit code. I must search the whois information for specific fields. How do I approach this when response = 0?
Solution:
import subprocess
# Set domain
hostname = "google.com"
# Query whois
response = subprocess.check_output(
"whois {hostname}".format(hostname=hostname),
stderr=subprocess.STDOUT,
shell=True)
# Check the response
print(response)
As pointed out below, subprocess.check_output() should be used rather than os.system.
Solution when looping:
for domain in domain_list:
hostname = domain
response = subprocess.run(
"whois {hostname}".format(hostname=hostname),
stderr=subprocess.STDOUT,
shell=True)
# Check the response
if response != 0:
available.append(hostname)
else:
continue
Subprocess.run() will continue the loop despite the != 0 response that occurs when a domain is unregistered.