Python:DNS查询:Pydns?挖?插座?

时间:2012-04-13 22:13:33

标签: python command-line dns

我正在尝试编写一个python脚本,它将接受一系列主机名的命令行参数并执行dns查询。如果查询成功,则不会发生任何事情,否则将抛出异常。以下是我到目前为止的情况:

#!/usr/bin/env python

   import socket
   import sys, os
   import DNS

   if len(sys.argv) <=3:
      print >>sys.stderr, 'usage:DnsCheck <hostname> <hostname> <hostname>'
      sys.exit(2)
   args = str(sys.argv[1:])
   command = "dig " + args

   def main(args):
      try:
         for i in args:
         #socket.gethostbyname(i)
         os.popen(command)
   except socket.error, e:
      print e

   if __name__ == '__main__':
      main(args)

1 个答案:

答案 0 :(得分:1)

import socket
import sys

def main():
    if len(sys.argv) < 2:
        print("Usage: dnscheck hostname [hostname...]")
    else:
        for host in sys.argv[1:]:
            try:
                ip = socket.gethostbyname(host)
                print("{} resolves to {}".format(host, ip))
            except socket.gaierror:
                print("Could not resolve {}".format(host))

if __name__=="__main__":
    main()