87 lines
2.1 KiB
Python
87 lines
2.1 KiB
Python
|
#!/usr/bin/python3
|
||
|
# -*- coding: utf-8 -*-
|
||
|
|
||
|
# Give me a random hostname!
|
||
|
|
||
|
import sys, os
|
||
|
import random
|
||
|
|
||
|
|
||
|
def read_file(filename) :
|
||
|
ret = []
|
||
|
with open(filename, 'r') as f_in :
|
||
|
for line in f_in.readlines():
|
||
|
line = line.strip()
|
||
|
# ignore empty lines or comment
|
||
|
if len(line) == 0 or line[0] in "#:!$%" : continue
|
||
|
ret.append(line)
|
||
|
return ret
|
||
|
|
||
|
def file_exists(filename) :
|
||
|
return os.path.exists(filename)
|
||
|
|
||
|
def scan_files(path, suffix = ".txt") :
|
||
|
ret = []
|
||
|
with os.scandir(path) as dirs:
|
||
|
for entry in dirs :
|
||
|
filename = entry.name
|
||
|
if filename.endswith(".txt") :
|
||
|
ret.append(filename)
|
||
|
return ret
|
||
|
|
||
|
def usage() :
|
||
|
print("print hostname suggestions")
|
||
|
print("Usage: %s [OPTIONS] [FILES...]" % (sys.argv[0]))
|
||
|
print("OPTIONS")
|
||
|
print(" -h, --help Print this help message")
|
||
|
print(" -l, --ls Print source files")
|
||
|
|
||
|
if __name__ == "__main__" :
|
||
|
# By default, print 10 lines, 4 entries each line
|
||
|
n = 10
|
||
|
c = 4
|
||
|
|
||
|
hostnames = []
|
||
|
filenames = []
|
||
|
|
||
|
args = sys.argv[1:]
|
||
|
for arg in args :
|
||
|
if arg == "" : continue
|
||
|
if arg[0] == '-' :
|
||
|
if arg == "-h" or arg == "--help" :
|
||
|
usage()
|
||
|
sys.exit(0)
|
||
|
elif arg == "-l" or arg == "--ls" :
|
||
|
for filename in scan_files(".") :
|
||
|
print(filename)
|
||
|
sys.exit(0)
|
||
|
else :
|
||
|
filenames.append(arg)
|
||
|
|
||
|
# If no files are given, take all files
|
||
|
if len(filenames) == 0 :
|
||
|
filenames = scan_files(".")
|
||
|
|
||
|
# Load hostnames from files
|
||
|
for filename in filenames :
|
||
|
# Add txt if not yet present
|
||
|
if not file_exists(filename) and not filename.endswith(".txt") :
|
||
|
if file_exists(filename + ".txt") : filename += ".txt"
|
||
|
if not file_exists(filename) :
|
||
|
sys.stderr.write("file not found: %s\n" % (filename))
|
||
|
sys.exit(1)
|
||
|
hostnames += read_file(filename)
|
||
|
|
||
|
if len(hostnames) == 0 :
|
||
|
sys.stderr.write("no hostnames found\n")
|
||
|
sys.exit(1)
|
||
|
|
||
|
for i in range(n) :
|
||
|
if len(hostnames) == 0 : break
|
||
|
for j in range(c) :
|
||
|
if len(hostnames) == 0 : break
|
||
|
hostname = hostnames[random.randint(0, len(hostnames)-1)]
|
||
|
hostnames.remove(hostname)
|
||
|
sys.stdout.write("%-20s" % (hostname))
|
||
|
sys.stdout.write("\n")
|