如何在python中正确执行host或dig命令

时间:2014-06-23 04:46:52

标签: python django ubuntu network-programming blacklist

我想使用python处理主机或挖掘命令,以检查域是否被列入黑名单。我用这些

surbl_result = os.system(host_str + ".multi.surbl.org")
#this works like performing a terminal command which is host johnnydeppsource.com.multi.surbl.org

它返回一个整数为0的响应(表示它列在黑名单中)或256(未列出)

if surbl_result == 0: #blacklisted in surbl
    black_list = True

但有时候,host命令失败并提供服务失败响应

Host johnnydeppsource.com.multi.surbl.org not found: 2(SERVFAIL)

这会返回一个零值,允许它添加新域,即使它被列入黑名单。还有其他方法可以执行此类操作吗?这包含在我的django 1.6应用程序中。任何线索都会有所帮助..

1 个答案:

答案 0 :(得分:1)

os.system(command)在子shell中执行命令(字符串)后返回exit_status。

最好以下面的方式使用:

from subprocess import Popen, PIPE
subproc = Popen(host_str + ".multi.surbl.org", stdout=PIPE, shell=True)
output, errorCode = subproc.communicate()
if errorCode == None:
    black_list = True