Created
September 25, 2023 15:02
-
-
Save fortran01/2abc9bc15011c76caaabf872ee051f09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Install required packages | |
pip install pyvmomi | |
pip install pandas | |
# Create the Python script file | |
cat > vm_performance.py << EOL | |
import pandas as pd | |
from pyVim.connect import SmartConnectNoSSL | |
from pyVmomi import vim | |
import atexit | |
import sys | |
from datetime import datetime, timedelta | |
import getpass | |
def main(): | |
host = input("Enter your vCenter host: ") | |
user = input("Enter your vCenter username: ") | |
password = getpass.getpass("Enter your vCenter password: ") | |
# Connect to vCenter | |
si = SmartConnectNoSSL(host=host, user=user, pwd=password) | |
atexit.register(si.content.sessionManager.Logout) | |
# Get the root folder | |
content = si.RetrieveContent() | |
container = content.rootFolder | |
# Create a view for VMs | |
view_manager = content.viewManager | |
view = view_manager.CreateContainerView(container, [vim.VirtualMachine], True) | |
# Specify the time range | |
hours = int(input("Enter the number of hours far back: ")) | |
end_time = datetime.now() | |
start_time = end_time - timedelta(hours=hours) | |
# Initialize an empty list to store the data | |
data = [] | |
# Iterate through VMs and collect CPU and memory usage data | |
for vm in view.view: | |
perf_manager = content.perfManager | |
metric_ids = [vim.PerformanceManager.MetricId(counterId=i, instance="*") for i in [2, 24]] # 2: CPU usage, 24: Memory usage | |
query_spec = vim.PerformanceManager.QuerySpec(entity=vm, metricId=metric_ids, intervalId=20, startTime=start_time, endTime=end_time, maxSample=1) | |
result = perf_manager.QueryPerf(query_spec=[query_spec]) | |
for r in result: | |
for val in r.value: | |
if val.id.counterId == 2: | |
cpu_usage = val.value[0] | |
elif val.id.counterId == 24: | |
memory_usage = val.value[0] | |
data.append([vm.name, cpu_usage, memory_usage]) | |
# Cleanup | |
view.Destroy() | |
# Create a DataFrame and save it to a CSV file | |
df = pd.DataFrame(data, columns=["VM Name", "CPU Usage (%)", "Memory Usage (%)"]) | |
df.to_csv("vm_performance.csv", index=False) | |
print("Data saved to vm_performance.csv") | |
if __name__ == "__main__": | |
main() | |
EOL | |
echo "Installation complete. Run the script with 'python vm_performance.py'" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment