我想编写一个 ip 更改程序,这很简单,但对我来说很有用,因为我需要多次更改我的 ip 地址。网上没找到简单实用的程序,所以写一个是我搜索的解决方案。
我发现 python 有 ifcfg、netifaces 和其他包,但每个包都有缺点,比如 ifcfg 输出网络掩码为 none,无论我有哪个网络掩码。
这是我目前编写的程序:
import ifcfg
import tkinter as tk
from tkinter import ttk
nic_list = []
root = tk.Tk() # GUI mode
root.geometry()
nic_frame = tk.Frame(root, bd=4, relief=tk.RAISED) # Frame for showing the nic interfaces in combobox
ip_frame = tk.Frame(root, bd=1, relief=tk.RAISED) # Frame for showing the ip addresses
buttons_frame = tk.Frame(root, bd=4, relief=tk.FLAT) # Frame for the buttons
nic_frame.grid(row=0,column=0)
ip_frame.grid(row=0,column=1)
buttons_frame.grid(row=1,column=0)
# Create a list of nic an ip addresses
options = {nic: interface['inet4'] for nic, interface in ifcfg.interfaces().items() if interface['inet4'] != []}
for nic in options.keys():
nic_list.append(nic)
# Show the nic names in a dropdown menu, first nic is the first nic that has an ip address.
if len(options)>0:
var = tk.StringVar(nic_frame)
var.set(nic_list[0])
w = ttk.Combobox(nic_frame, values=nic_list)
w.current(0)
else:
var = tk.StringVar(nic_frame)
var.set("")
w = ttk.Combobox(nic_frame, values=options)
w.pack()
#show the ip addresses of the selected nic
for ip in options[w.get()]:
ip_addrs = tk.Label(ip_frame, text = ip, pady=2)
ip_addrs.pack(padx=30)
# Buttons
add_ip_button = tk.Button(buttons_frame, text="Add", command=add_ip, bd=2, font=("david", 12)).grid(row=0,column=0)
edit_ip_button = tk.Button(buttons_frame, text="Edit", bd=2, font=("david", 12)).grid(row=0,column=1)
quit_button = tk.Button(buttons_frame, text="Quit", bd=2, font=("david", 12), command=root.destroy).grid(row=0,column=2)
root.mainloop()
我想要一个程序,它首先向我显示所选接口的所有 ip 地址,包括 CIDR 或网络掩码,然后用户可以更改/添加 ip 地址。 /i/ 怎么办?