When we (my partner and I) started coding the project, we decided Python would be our primary language, since we both know it, and it makes life easy. This was true, even on the difficult parts of using a database (MySQL), connecting to SMTP/IMAP/POP3 server, etc.
Last week I stumbled into a block, when querying a DNS server was required. Usually, I'd use the output of 'dig' or 'host', but I cannot be sure the project would run on a platform that has those tools. My second try was to use Python modules (pydns etc.) which should solve this problem, but they were all buggy/undocumented/not-working/too-complicated-to-use.
The annoying part is that I know how to do what I want in Perl:
use Net::DNS;
my $res = Net::DNS::Resolver->new;
my $answer = $res->search('gmail.com', 'TXT');
print $answer->string;
And that's it. 4 lines of code. Still I hadn't found a decent Python-way to do this. So now I'm using Pydig to query DNS servers. Over 1200 lines of code. Pretty big hammer to solve a tiny problem.
If any of you know a better way to do this in Python, I'd love to hear about it.
a. Why, of all records, did you choose TXT record? :)
ReplyDeleteb. In most cases I find it smarter to use gethostbyname(). It's much nicer (higher level, takes into account /etc/hosts, etc etc)
But, of course, maybe in your cases you needed direct DNS access.
thanks for the comment.
ReplyDeletewhile gethostbyname would return the IP address of a host, this wouldn't suffice. the TXT record of mail domains contain valuable information (read about SPF, DKIM etc.) which i must get.
as for now, i run system command. on windows it's nslookup and on linux it's host/dig.
Use dnspython (http://www.dnspython.org/) and then do something like this:
ReplyDeleteimport dns.resolver
answers = dns.resolver.query(hostname, 'TXT')
text = str(answers[0])
if text and len(text) > 2:
text = text[1:-1]