pythondatetimestructautomationpsutil

Python code to retrieve system info in format


I have to make a python script for a course I’m doing. It has to retrieve the following:

And print to a csv with the following formats:

PF1VKNRQ, 192.168.1.2, 54-05-DB-3B-71-31, i7, Windows 10, 6//10/2023 8:00:01, 3Mb/s, 21;25;443;1234 

Code I have so far is:

import csv
import os
import platform
import psutil
import socket
import struct 
import datetime

def get_system_info():
    system_info = {}

    system_info['Computer_Name'] = platform.node()
    system_info['IP_Address'] = 
    system_info['MAC_Address'] = 
    system_info['Processor_Model'] = 
    system_info['OS'] = platform.system() + platform.version([release])
    system_info[ 'Sys_Time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    system_info['Net_Con_Spd'] = 
    system_info['Active_Ports'] = 
    print(system_info)

get_system_info()

Can anyone help me find out how to fill in the other details to meet the reporting requirements?


Solution

  • I had solved a similar one for my project. Let me know if this works, first install the following libraries: pip install psutil speedtest-cli

    import csv
    import os
    import platform
    import psutil
    import socket
    import datetime
    import subprocess
    import uuid
    
    def get_system_info():
        system_info = {}
        system_info["Computer_Name"] = platform.node()
        system_info["IP_Address"] = socket.gethostbyname(socket.gethostname())
        system_info["MAC_Address"] = ':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff) for elements in range(0,2*6,2)][::-1])
        system_info["Processor_Model"] = platform.processor()
        system_info["OS"] = platform.system() + " " + platform.version()
        system_info["Sys_Time"] = datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
        try:
            result = subprocess.run(['speedtest', '--simple'], stdout=subprocess.PIPE, text=True)
            download_speed = None
            for line in result.stdout.splitlines():
                if 'Download' in line:
                    download_speed = line.split()[1]
                    break
            system_info["Net_Con_Spd"] = download_speed
        except Exception as e:
            system_info["Net_Con_Spd"] = "Error retrieving speed"
        active_ports = []
        for conn in psutil.net_connections(kind='inet'):
            active_ports.append(str(conn.laddr.port))
        system_info["Active_Ports"] = ';'.join(active_ports)
        return system_info
    
    def write_to_csv(system_info):
        with open('system_info.csv', mode='w', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(system_info.keys())
            writer.writerow(system_info.values())
    
    if __name__ == "__main__":
        system_info = get_system_info()
        write_to_csv(system_info)