如何在python中将系统信息写入电子表格

时间:2017-12-11 20:47:20

标签: python python-2.7 export-to-csv

我正在尝试将系统信息写入电子表格。但是当我尝试使用我的变量时,它们会出现黑色

导入csv     进口口     import linecache

os.system('getmac -v > mac.txt')
os.system("wmic bios get serialnumber > serial.txt")
os.system("wmic computersystem get model > model.txt")
os.system("hostname > hostname.txt")
os.system("ipconfig > ip.txt")


open('ip1.txt','w').writelines([line for line in open('ip.txt')if 'IPv4' in line])
open('mac1.txt','w').writelines([line for line in open('mac.txt')if 'Wi-Fi' in line])
open('mac2.txt','w').writelines([line for line in open('mac.txt')if 'Ethernet' in line])

serial = linecache.getline('serial.txt', 3)
model = linecache.getline('model.txt', 3)

mac = open("mac.txt","r")
IP = open("ip1.txt","r")
mac1 = open("mac1.txt","r")
mac2 = open("mac2.txt","r")
hostname = open("hostname.txt","r")



Rmac = mac.read()
Rip = IP.read()
Rmac1 = mac1.read()
Rmac2 = mac2.read()
Rhostname = hostname.read()



myData = [[model]]

myFile = open('example2.csv', 'w')
with myFile:
    writer = csv.writer(myFile)
    writer.writerows(myData)

这只是不会将信息写入电子表格?我究竟做错了什么?我是编程btw的新手

1 个答案:

答案 0 :(得分:0)

您不需要中间文件,为什么不立即调用您的命令并将其信​​息写入您的CSV而不进行前后跳舞?

import csv
import subprocess

# get the model
model = subprocess.check_output(["WMIC", "computersystem", "get", "model"],
                                universal_newlines=True).strip().rsplit("\n", 1)[1]
# get the serial
serial = subprocess.check_output(["WMIC", "bios", "get", "serialnumber"],
                                 universal_newlines=True).strip().rsplit("\n", 1)[1]
# get the host name
hostname = subprocess.check_output(["hostname"], universal_newlines=True).strip()

# get WMI output for all addresses
ips = subprocess.check_output(["WMIC", "NICCONFIG", "where", "IPEnabled=true",
                               "get", "IPAddress"],
                              universal_newlines=True).strip().split("\n\n")[1:]
# post-process to get the addresses only
ips = [ip.split(",")[0].strip('"{} ') for ip in ips]

# etc.

with open("example2.csv", "wb") as f:  # open your CSV for writing
    writer = csv.writer(f)  # create a writer
    # you didn't write a header but let's add it in
    writer.writerow(["model", "serial", "hostname", "ips"])  # etc., you get the picture...
    writer.writerow([model, serial, hostname, ",".join(ips)])  # add other columns, too

你会得到一个很好的example2.csv包含:

model,serial,hostname,ips
Your Model,Your Serial,Your-Hostname,List.Of.IP.Addresses

对其他字段执行相同的操作并完成。