Ticket #5596: gethostbyname-exit-5596-4.patch

File gethostbyname-exit-5596-4.patch, 9.6 KB (added by Richard Wall, 7 years ago)

Updated the other names examples to use task.react

  • doc/names/examples/dns-service.py

    === modified file 'doc/names/examples/dns-service.py'
     
    44# See LICENSE for details.
    55
    66"""
    7 Sample app to lookup SRV records in DNS.
    8 To run this script:
    9 $ python dns-service.py <service> <proto> <domain>
    10 where,
    11 service = the symbolic name of the desired service.
    12 proto = the transport protocol of the desired service; this is usually either TCP or UDP.
    13 domain =  the domain name for which this record is valid.
    14 e.g.:
    15 $ python dns-service.py sip udp yahoo.com
    16 $ python dns-service.py xmpp-client tcp gmail.com
     7USAGE: python dns-service.py SERVICE PROTO DOMAINNAME
     8
     9Print the SRV records for a given DOMAINNAME eg
     10
     11 python dns-service.py xmpp-client tcp gmail.com
     12
     13SERVICE: the symbolic name of the desired service.
     14
     15PROTO: the transport protocol of the desired service; this is usually
     16       either TCP or UDP.
     17
     18DOMAINNAME: the domain name for which this record is valid.
    1719"""
    18 
    19 from twisted.names import client
    20 from twisted.internet import reactor
    2120import sys
    2221
    23 def printAnswer((answers, auth, add)):
    24     if not len(answers):
    25         print 'No answers'
     22from twisted.names import client, error
     23from twisted.internet.task import react
     24
     25
     26def printResult(records, domainname):
     27    """
     28    Print the SRV records for the domainname or an error message if no
     29    SRV records were found.
     30    """
     31    answers, authority, additional = records
     32    if answers:
     33        sys.stdout.write(
     34            domainname + ' IN \n ' +
     35            '\n '.join(str(x.payload) for x in answers) +
     36            '\n')
    2637    else:
    27         print '\n'.join([str(x.payload) for x in answers])
    28     reactor.stop()
    29 
    30 def printFailure(arg):
    31     print "error: could not resolve:", arg
    32     reactor.stop()
    33 
    34 try:
    35     service, proto, domain = sys.argv[1:]
    36 except ValueError:
    37     sys.stderr.write('%s: usage:\n' % sys.argv[0] +
    38                      '  %s SERVICE PROTO DOMAIN\n' % sys.argv[0])
    39     sys.exit(1)
    40 
    41 resolver = client.Resolver('/etc/resolv.conf')
    42 d = resolver.lookupService('_%s._%s.%s' % (service, proto, domain), [1])
    43 d.addCallbacks(printAnswer, printFailure)
    44 
    45 reactor.run()
     38        sys.stderr.write(
     39            'ERROR: No SRV records found for name %r\n' % (domainname,))
     40
     41
     42def printError(failure, domainname):
     43    """
     44    Print a friendly error message if the domainname could not be
     45    resolved.
     46    """
     47    failure.trap(error.DNSNameError)
     48    sys.stderr.write('ERROR: domain name not found %r\n' % (domainname,))
     49
     50
     51def main(reactor, *argv):
     52    try:
     53        service, proto, domainname = sys.argv[1:]
     54    except ValueError:
     55        sys.stderr.write(
     56            __doc__.lstrip() + '\n'
     57            'ERROR: incorrect command line arguments\n')
     58        raise SystemExit(1)
     59
     60    resolver = client.Resolver('/etc/resolv.conf')
     61    domainname = '_%s._%s.%s' % (service, proto, domainname)
     62    d = resolver.lookupService(domainname)
     63    d.addCallback(printResult, domainname)
     64    d.addErrback(printError, domainname)
     65    return d
     66
     67if __name__ == '__main__':
     68    react(main, sys.argv[1:])
  • doc/names/examples/gethostbyname.py

    === modified file 'doc/names/examples/gethostbyname.py'
     
    44# See LICENSE for details.
    55
    66"""
    7 Returns the IP address for a given hostname.
    8 To run this script:
    9 $ python gethostbyname.py <hostname>
    10 e.g.:
    11 $ python gethostbyname.py www.google.com
     7USAGE: python gethostbyname.py HOSTNAME
     8
     9Print the IP address for a given hostname. eg
     10
     11 python gethostbyname.py www.google.com
     12
     13This script does a host lookup using the default Twisted Names
     14resolver, a chained resolver, which attempts to lookup a name from:
     15 * local hosts file
     16 * memory cache of previous lookup results
     17 * system recursive DNS servers
    1218"""
    1319import sys
    14 from twisted.names import client
    15 from twisted.internet import reactor
    16 
    17 def gotResult(result):
    18     print result
    19     reactor.stop()
    20 
    21 def gotFailure(failure):
    22     failure.printTraceback()
    23     reactor.stop()
    24 
    25 d = client.getHostByName(sys.argv[1])
    26 d.addCallbacks(gotResult, gotFailure)
    27 
    28 reactor.run()
     20
     21from twisted.names import client, error
     22from twisted.internet.task import react
     23
     24
     25def printResult(address, hostname):
     26    """
     27    Print the IP address or an error message if an IP address was not
     28    found.
     29    """
     30    if address:
     31        sys.stdout.write(address + '\n')
     32    else:
     33        sys.stderr.write(
     34            'ERROR: No IP adresses found for name %r\n' % (hostname,))
     35
     36
     37def printError(failure, hostname):
     38    """
     39    Print a friendly error message if the hostname could not be
     40    resolved.
     41    """
     42    failure.trap(error.DNSNameError)
     43    sys.stderr.write('ERROR: hostname not found %r\n' % (hostname,))
     44
     45
     46def main(reactor, *argv):
     47    try:
     48        hostname = argv[0]
     49    except IndexError:
     50        sys.stderr.write(
     51            __doc__.lstrip() + '\n'
     52            'ERROR: missing HOSTNAME argument\n')
     53        raise SystemExit(1)
     54
     55    d = client.getHostByName(hostname)
     56    d.addCallback(printResult, hostname)
     57    d.addErrback(printError, hostname)
     58    return d
     59
     60if __name__ == '__main__':
     61    react(main, sys.argv[1:])
  • doc/names/examples/index.xhtml

    === modified file 'doc/names/examples/index.xhtml'
     
    1212
    1313    <h2>DNS (Twisted Names)</h2>
    1414    <ul>
    15         <li><a href="testdns.py">testdns.py</a> - Prints the results of an Address record lookup, Mail-Exchanger record lookup, and Nameserver record lookup for the given hostname for a given hostname.</li>
     15        <li><a href="testdns.py">testdns.py</a> - Prints the results of an Address record lookup, Mail-Exchanger record lookup, and Nameserver record lookup for the given domain name.</li>
    1616        <li><a href="dns-service.py">dns-service.py</a> - Searches for SRV records in DNS.</li>
    1717        <li><a href="gethostbyname.py">gethostbyname.py</a> - Returns the IP address for a given hostname.</li>
    1818    </ul>
    1919</body>
    2020</html>
    21 
  • doc/names/examples/testdns.py

    === modified file 'doc/names/examples/testdns.py'
     
    44# See LICENSE for details.
    55
    66"""
    7 Prints the results of an Address record lookup, Mail-Exchanger record
    8 lookup, and Nameserver record lookup for the given hostname for a
    9 given hostname.
    10 
    11 To run this script:
    12 $ python testdns.py <hostname>
    13 e.g.:
    14 $ python testdns.py www.google.com
     7USAGE: python testdns.py DOMAINNAME
     8
     9Print the Address records, Mail-Exchanger records and the Nameserver
     10records for the given domain name. eg
     11
     12 python testdns.py google.com
    1513"""
    1614import sys
    1715
    18 from twisted.names import client
    19 from twisted.internet import defer, reactor
    20 from twisted.names import dns, error
    21 
    22 
    23 r = client.Resolver('/etc/resolv.conf')
    24 
    25 
    26 def formatResult(a, heading):
    27     answer, authority, additional = a
     16from twisted.internet import defer
     17from twisted.internet.task import react
     18from twisted.names import client, dns, error
     19
     20
     21def formatRecords(records, heading):
     22    """
     23    Extract only the answer records and return them as a neatly
     24    formatted string beneath the given heading.
     25    """
     26    answers, authority, additional = records
    2827    lines = ['# ' + heading]
    29     for a in answer:
     28    for a in answers:
    3029        line = [
    3130            a.name,
    3231            dns.QUERY_CLASSES.get(a.cls, 'UNKNOWN (%d)' % (a.cls,)),
     
    3635    return '\n'.join(line for line in lines)
    3736
    3837
    39 def printError(f):
    40     f.trap(defer.FirstError)
    41     f = f.value.subFailure
    42     f.trap(error.DomainError)
    43     print f.value.__class__.__name__, f.value.message.queries
    44 
    45 
    46 def printResults(res):
    47     for r in res:
    48         print r
    49         print
    50 
    51 
    52 if __name__ == '__main__':
    53     domainname = sys.argv[1]
    54 
     38def printResults(results, domainname):
     39    """
     40    Print the formatted results for each DNS record type.
     41    """
     42    sys.stdout.write('# Domain Summary for %r\n' % (domainname,))
     43    sys.stdout.write('\n\n'.join(results) + '\n')
     44
     45
     46def printError(failure, domainname):
     47    """
     48    Print a friendly error message if the hostname could not be
     49    resolved.
     50    """
     51    failure.trap(defer.FirstError)
     52    failure = failure.value.subFailure
     53    failure.trap(error.DNSNameError)
     54    sys.stderr.write('ERROR: domain name not found %r\n' % (domainname,))
     55
     56
     57def main(reactor, *argv):
     58    try:
     59        domainname = argv[0]
     60    except IndexError:
     61        sys.stderr.write(
     62            __doc__.lstrip() + '\n'
     63            'ERROR: missing DOMAINNAME argument\n')
     64        raise SystemExit(1)
     65
     66    r = client.Resolver('/etc/resolv.conf')
    5567    d = defer.gatherResults([
    5668            r.lookupAddress(domainname).addCallback(
    57                 formatResult, 'Addresses'),
     69                formatRecords, 'Addresses'),
    5870            r.lookupMailExchange(domainname).addCallback(
    59                 formatResult, 'Mail Exchangers'),
     71                formatRecords, 'Mail Exchangers'),
    6072            r.lookupNameservers(domainname).addCallback(
    61                 formatResult, 'Nameservers'),
     73                formatRecords, 'Nameservers'),
    6274            ], consumeErrors=True)
    6375
    64     d.addCallbacks(printResults, printError)
    65 
    66     d.addBoth(lambda ign: reactor.stop())
    67 
    68     reactor.run()
     76    d.addCallback(printResults, domainname)
     77    d.addErrback(printError, domainname)
     78    return d
     79
     80
     81if __name__ == '__main__':
     82    react(main, sys.argv[1:])