When calling a function, how to feed variable as an arg

3010 views python-3.6
-5

I have the code below that works, but instead of calling the function with "www.google.com", i need to be able to pass as arg:

python certexp.py www.google.com:

import ssl
import OpenSSL
import time
def get_SSL_Expiry_Date(host, port):
    cert = ssl.get_server_certificate((host, 443))
    x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
    raw_date = x509.get_notAfter()
    decoded_date = raw_date.decode("utf-8")
    print (decoded_date)
    dexpires = time.strptime(decoded_date, "%Y%m%d%H%M%Sz")
    print (dexpires.tm_mon,"/",dexpires.tm_mday,"/",dexpires.tm_year)

get_SSL_Expiry_Date("google.com", 443)

Thank you

answered question

1 Answer

8

In python the sys module handles command line arguments.

This gives you an array of command line parameters, with sys.argv[0] being the name of the executable, then any subsequent elements being user parameters.

This makes your code:

import ssl import OpenSSL import time import sys

def get_SSL_Expiry_Date(host, port):
    cert = ssl.get_server_certificate((host, 443))
    x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
    raw_date = x509.get_notAfter()
    decoded_date = raw_date.decode("utf-8")
    print (decoded_date)
    dexpires = time.strptime(decoded_date, "%Y%m%d%H%M%Sz")
    print (dexpires.tm_mon,"/",dexpires.tm_mday,"/",dexpires.tm_year)

if (len(sys.argv) == 1):
    sys.stderr.write("%s: Give hostname as an argument, optionally a port too" % (sys.argv[0]))
    sys.exit(1)

hostname = sys.argv[1]
port = 443
if (len(sys.argv) == 3):
    port = int(sys.argv[2])

get_SSL_Expiry_Date(hostname, port)

Obviously you could do that for the port too. There's other command line parsing modules too, so you can say --port= etc.

posted this

Have an answer?

JD

Please login first before posting an answer.