-1

我正在尝试编写一个 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)
4

1 回答 1

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()
于 2012-04-13T23:58:05.890 回答