'Reading Server list as input from notepad or excel - Python
I'm new to python. Recently I created a Health Check script in python which is useful for fetching details for the base machine. But I want to use it for fetching details from Remote Windows and Linux Servers. In powershell script, we used to enter server name or IP address in a excel or notepad for script to read and fetch the server details from there. Is there any way in python for fetching the server details one by one from a notepad or excel and provide health check details for it?
Solution 1:[1]
Yes, there is a way to read data from a notepad file or excel file in Python.
JSON files
The first question is: does this file have any established structure or can you choose how this file will look like?
If you can choose what the file will look like, then I think it will be the simplest and easiest to read if you use JSON to store this data. JSON is a notation to store some data that you can easily read with a programming language. The JSON file name ends with .json (e.g. "servers.json"). If you store it in a normal .txt file (Notepad) or .xls (Excel), then you can surely read that with Python too, but it will be simpler if you store in JSON.
This is how this JSON file can look like:
[
"243.240.94.92",
"183.80.15.155",
"66.49.192.233",
"175.209.93.76",
"123.91.228.104"
]
This represents an array with IP addresses. You can read it in Python in the following way:
import json
with open('path_to_file/servers.json') as f:
data = json.load(f)
After that, data
will be an array containing the IP addresses from the file.
The first line imports Json package/module so that you can use its functions. The second line reads the content of the file. The third line passes the content of the file to the json.load
function which converts the content to a Python object.
You can print the variable data
to see what it exactly contains.
print(data)
You can learn about JSON more for example here: https://www.programiz.com/python-programming/json
Here's an example of script that reads this IP addresses from servers.json file and prints IP addresses one by one:
import json
with open('path_to_file/servers.json') as f:
data = json.load(f)
for ip_address in data:
print("IP Address: " + ip_address)
TXT files (notepad)
The easiest way to read .txt file is like that:
with open('path_to_file/servers.txt') as f:
data = f.read()
After that, data
variable will contain the content of the file. Print that variable, if you want to see what variable contains exactly.
The problem is that it will store the data as a string, so you will have to parse it (convert it into format that you prefer) so that you can do something with it. That's why I said it's simpler with JSON.
CSV or XLS file (Excel)
For reading excel files, you will find your answer here:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |