簡體   English   中英

Python Shell 腳本。 鏈式 Unix OpenSSL 命令

[英]Python Shell Scripting. Chain Unix OpenSSL Commands

我正在嘗試編寫一個簡單的 Python shell 腳本,該腳本將接受用戶輸入的服務器名稱和端口號,並將其路由到顯示 SSL 證書到期信息的 OpenSSL 命令中。

我正在使用 subprocess 模塊,但是我不清楚將命令與用戶輸入的信息鏈接的正確方法。

完整的命令是:

echo | openssl s_client -servername www.google.com -connect www.google.com:443 2>/dev/null | openssl x509 -noout -dates

命令的輸出(這是我希望腳本輸出的內容):

notBefore=May 31 16:57:23 2017 GMT
notAfter=Aug 23 16:32:00 2017 GMT

我的代碼:

#!/usr/bin/env python
import subprocess 

server_name = raw_input("Enter server name: ")
port_number = raw_input("Enter port number: ")

def display_cert_info(servername, portnum):
    pn = str(server_name + ":" + port_number)
    cmd = ["echo", "|", "openssl", "s_client", "-servername", str(servername), "-connect", pn, "2>/dev/null", "|", "openssl", "x509", "-noout", "-dates"]

    info = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = info.communicate()[0]
    print(output)

display_cert_info(server_name, port_number)

任何幫助表示贊賞!

與 shell 不同,標准輸入、標准輸出和標准錯誤都由Popenstdinstdoutstderr參數處理。 因此,您可以丟棄前兩個命令元素 ( echo | )。 然后,您需要使用管道中的最后一個命令運行一個單獨的進程,將第一個命令的輸出放入其stdin 通常,在以另一種語言運行時,您不使用 shell 管道,而是使用該語言自己的管道(或流)機制。

@Han 我意識到我參加聚會可能有點晚了,無法為您提供幫助,很抱歉,但這是為其他尋求此解決方案的人准備的。 我必須將 Popen() 和 check_output() 函數串在一起,如下所示:

#!/usr/bin/python3
from subprocess import Popen, PIPE, check_output
from os import open, O_WRONLY

servers = [
    "server1.domain.com",
    "server2.domain.com",
    "server3.domain.com"
    ]

for s in servers:
    print("querying {}".format(s))
    dn = open("/dev/null", O_WRONLY)
    q = Popen(["/usr/bin/openssl", "s_client", "-servername", s, "-connect","{}:443".format(s)], stdout=PIPE, stdin=PIPE, stderr=dn, shell=False)
    y = check_output(["/usr/bin/openssl", "x509", "-noout", "-dates"], stdin=q.stdout)
    print(y.decode("utf-8"))

這讓我可以對我添加到列表中的所有服務器進行快速而骯臟的審計。 我的下一次迭代是向輸出添加監控/警報,並且再也不會對過期的證書感到驚訝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM