从文本文件传递参数时,Python脚本不起作用

时间:2018-08-01 22:29:07

标签: python sql json python-3.x

我有一个python脚本,该脚本应该遍历文本文件,并从文本文件中的每一行收集域作为参数。然后,应该使用域作为SQL查询中的参数。问题是当我将域作为参数传递时,脚本生成的JSON输出为空白。如果我直接在查询中的SQL查询中设置domain_name参数,则脚本将输出完美的JSON格式。正如您在def connect_to_db()下方的脚本顶部所看到的那样,我开始循环浏览文本文件。我不确定在任何帮助下发生错误的代码将不胜感激!

代码

from __future__ import print_function

try:
    import psycopg2
except ImportError:
    raise ImportError('\n\033[33mpsycopg2 library missing. pip install psycopg2\033[1;m\n')
    sys.exit(1)

import re
import sys
import json
import pprint

DB_HOST = 'crt.sh'
DB_NAME = 'certwatch'
DB_USER = 'guest'


def connect_to_db():
    filepath = 'test.txt'
    with open(filepath) as fp:
        for cnt, domain_name in enumerate(fp):
            print("Line {}: {}".format(cnt, domain_name))
            print(domain_name)
            domain_name = domain_name.rstrip()

            conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST))
            cursor = conn.cursor()
            cursor.execute(
                "SELECT c.id, x509_commonName(c.certificate), x509_issuerName(c.certificate) FROM certificate c, certificate_identity ci WHERE c.id = ci.certificate_id AND ci.name_type = 'dNSName' AND lower(ci.name_value) = lower('**domain_name**') AND x509_notAfter(c.certificate) > statement_timestamp();")

            unique_domains = cursor.fetchall()

        # print out the records using pretty print
        # note that the NAMES of the columns are not shown, instead just indexes.
        # for most people this isn't very useful so we'll show you how to return
        # columns as a dictionary (hash) in the next example.
            pprint.pprint(unique_domains)

            outfilepath = domain_name + ".json"
            with open(outfilepath, 'a') as outfile:
                    outfile.write(json.dumps(unique_domains, sort_keys=True, indent=4))

if __name__ == "__main__":
#    filepath = 'test.txt'
#    with open(filepath) as fp:
#        for cnt, domain_name in enumerate(fp):
#            print("Line {}: {}".format(cnt, domain_name))
#            print(domain_name)
#            domain_name = domain_name.rstrip()
    connect_to_db()

0 个答案:

没有答案