I have a csv file with information about some computers on our network. I'd like to be able to type from the command line a quick line to bring me back the relevant items from the csv. In the format:
$ tag.py *hostname*
The csv has about 50 columns with information ranging from MAC address to last time seen on the network. I only want to output a selection of these columns when I search. I've written the necessary code and it works. However I want the search to be more flexible. As it stands, the search term needs to be exactly the same as the value I'm searching for. aka
$ tag.py mycomputer # This returns nothing
$ tag.py mycomputer.co.uk # This returns the information I want
$ tag.py 63746 # This returns nothing
$ tag.py 00063746 # This returns the information I want
So now for the code I have.
# Import Modules
import sys
import csv
# Get user Input
# I assume the script is used in the form script.py "search-term"
# If no input added to command, ask for user input
if len(sys.argv) < 2:
print("Please enter a hostname or asset number.")
search_1 = input("Search for:")
else:
search_1=sys.argv[1]
# Setup Variables
# Open cvs and setup csv.reader settings
csvfile = open("file.csv", "r", encoding="Latin-1")
csvfile.seek
reader = csv.reader(csvfile, dialect='excel', delimiter=",", quotechar="'")
# Search cvs for the input string
for line in reader:
if search_1 in line:
print("------------------------------------------------------")
print(" Hostname = " + line[10])
print(" " + line[11])
print(" AssetId = " + line[30])
print(" IP = " + line[7])
print(" MAC = " + line[6])
print(" Owner = " + line[15])
print(" Username = " +line[14])
print(" Tel = " + line[17])
print(" Last Seen = " + line[27])
print("------------------------------------------------------")
csvfile.close()
I would like the code to be able to ignore the fqdn if I search for a hostname or to add the extra 0 characters to the asset number. I think I can fix the asset number issue with a len(search_1) < 8
append some 0
to the front until it is 8 characters long but that's avoiding the fact that I really would prefer to just search for the string without manipulating it to match the thing I'm looking for.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…