Rewrite siprun with argparse

This commit is contained in:
Marcel Nijenhof
2020-07-26 12:55:12 +02:00
parent 1c574329ea
commit 4adb8eeca6

78
siprun
View File

@@ -2,66 +2,39 @@
import sys
import getopt
import argparse
from lmwsip import LmwSip
def usage():
print("siprun [-H] [-s] [-d <date>] [-t <time>] [-h <host>] [-p <port>] [<files>]")
print("\t-H: Show usage")
print("\t-s: SSL connection")
print("\t-d <date>: Date replacement string (2019-02-14)")
print("\t-t <time>: Time replacement string (17:00)")
print("\t-h <host>: Connect to host")
print("\t-p <port>: Connect to port")
print("\t-<files>: LMW commando files")
def main():
lastTime=LmwSip.lasttime(None, "H10")
parser = argparse.ArgumentParser(description="Run a sip file.")
parser.add_argument("-u", "--unencrypted", action="store_true",
help="Run a sip connection without ssl")
parser.add_argument("-H", "--host", action='store',
default="sip-lmw.rws.nl",
help="Host to connect to")
parser.add_argument("-p", "--port", action='store', type=int, default=443,
help="Port to connect to")
parser.add_argument("-d", "--date", action='store',
default=lastTime["day"],
help="Date replacement string [DD-MM-YYYY]")
parser.add_argument("-t", "--time", action='store',
default=lastTime["time_of_day"],
help="Time replacement string [HH:MM]")
parser.add_argument("files", type=argparse.FileType('r'), nargs="+",
help="Sip files to run")
args = parser.parse_args()
try:
opts, args = getopt.getopt(sys.argv[1:], "sh:p:d:t:", ["help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
print(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
ssl=False
time=None
date=None
host=None
port=None
for o, a in opts:
if o == "-H":
usage()
sys.exit(0)
elif o == "-s":
ssl=True
elif o == "-d":
date=a
elif o == "-t":
time=a
elif o == "-h":
host=a
elif o == "-p":
port=a
if (host==None or port==None):
print("Set host and port")
usage()
sys.exit(3)
try:
lmwsip = LmwSip(ssl=ssl, host=host, port=port)
lmwsip = LmwSip(host=args.host, port=args.port,
ssl=not args.unencrypted)
except Exception as e:
print("Connect to lmw failed: %s" % e)
exit(1)
if (date == None or time == None):
# We assume a 10 minut interval so we use H10
r = lmwsip.lasttime("H10")
if (date == None):
date = r["day"]
if (time == None):
time = r["time_of_day"]
for cmdfile in args:
with open(cmdfile, "r") as f:
for f in args.files:
for cmd in f:
cmd = cmd.replace('{DATE}', date)
cmd = cmd.replace('{TIME}', time)
cmd = cmd.replace('{DATE}', args.date)
cmd = cmd.replace('{TIME}', args.time)
cmd = cmd.replace('\n', '\r')
print("> [%s]" % (cmd.strip('\r')))
try:
@@ -69,7 +42,6 @@ def main():
print("< [%s]" % (lmwsip.recv().strip('\r')))
except:
pass
f.close()
if __name__ == "__main__":
main()