Python将多个变量输出到文本文件

时间:2018-08-30 15:27:40

标签: python

尝试遍历服务器列表并使用OpenSSL连接到它们,检索SSL证书,并提取服务器名称,证书到期的日期,并计算证书到期之前的天数。该代码可以在终端会话上正常打印,但是我无法以这种格式将其写入每个服务器的文本文件: 服务器名称:Server01 日证书过期:2020-03-16 23:59:59 过期天数:564 有人可以告诉我如何捕获For循环中的每个变量并将其写入文本文件吗?我尝试了多种尝试,尝试使用f.write的变体,但似乎无法使其正常工作。

f = open("SSL.txt", "a")
f.write(server_name, exp_date, days_to_expire) 

完整代码

import ssl
from datetime import datetime
import pytz
import OpenSSL
import socket
from datetime import timedelta
import colorama
from colorama import init
from colorama import Fore, Back, Style

## opening file
ipfile = open('server_ip.txt')
cur_date = datetime.utcnow()

for ip in ipfile:
  try:
    host = ip.strip().split(":")[0]
    port = ip.strip().split(":")[1]
    print("\nChecking certifcate for server ", host)
    ctx = OpenSSL.SSL.Context(ssl.PROTOCOL_TLSv1)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, int(port)))
    cnx = OpenSSL.SSL.Connection(ctx, s)
    cnx.set_connect_state()
    cnx.do_handshake()
    cert = cnx.get_peer_certificate()
    s.close()
    server_name = cert.get_subject().commonName
    print(server_name)
    edate = cert.get_notAfter()
    edate = edate.decode()
    exp_date = datetime.strptime(edate, '%Y%m%d%H%M%SZ')
    days_to_expire = int((exp_date - cur_date).days)
    print(exp_date)
    print("day to expire", days_to_expire)
    if days_to_expire <= 30:
      init(convert=True)
      print(Fore.YELLOW + "WARNING!",server_name, "SSL Certificate has less than 30 days before it expires." + Style.RESET_ALL)
  except:
      print("error on connection to Server,", host)

2 个答案:

答案 0 :(得分:0)

请不要忘记通过f.close()关闭文件,否则文件将为空。如果使用with关键字,文件将自动关闭,如从The Python Tutorial 7.1 Reading and Writing Files复制的以下示例代码所示:

>>> with open('workfile') as f:
...     read_data = f.read()
>>> f.closed
True

此外,write方法仅接受1个参数。

答案 1 :(得分:0)

根据Victor关于关闭文件的评论,要在写入时将多个变量传递给您,可以使用python 3的字符串插值。

例如:

>>> f = open('test.txt', 'a')
>>> for x in range(10):
...     y = str(1*x)
...     z = str(10* x)
...     j = str(100*x)
...     f.write(f"{y} {z} {j}\n")
>>> f.close()