问题描述
我建立了一个类来更改我的mac地址(不确定这是否是最干净的方法)
#!/usr/bin/env python3
import subprocess
class MacAdress:
global interface
interface = input("enter interface:\t")
def change_Mac(self=interface):
mac = '00:11:22:ff:ff:ff'
subprocess.call(f"sudo -S ifconfig {interface} down",shell=True)
subprocess.call(f'sudo -S ifconfig {interface} hw ether {mac}',shell=True)
subprocess.call(f"sudo -S ifconfig {interface} up",shell=True)
def Restore_Mac(self=interface):
old_mac = ''
subprocess.call(f"sudo -S ifconfig {interface} down",shell=True)
subprocess.call(f'sudo -S ifconfig {interface} hw ether {old_mac}',shell=True)
我想知道是否有一种方法可以存储root密码,因此它只提示一次类似于 interface 的用法,而不是使用 sudo -S 每个命令。旧Mac 特意留为空白。任何将其清理成更专业的技巧也将不胜感激。
解决方法
#!/usr/bin/env python3
import subprocess,optparse,getpass
def get_arguments():
parser = optparse.OptionParser()
parser.add_option("-i","--interface",dest="interface",help="Interface to change MAC address eg. eth0 wlan0")
parser.add_option("-m","--mac",dest="new_mac",help="New Mac Address")
(options,arguments) = parser.parse_args()
if not options.interface:
parser.error("Please specify an interface with -i or --interface use --help for more info")
elif not options.new_mac:
parser.error("Please specify an new mac with -m or --mac use --help for more info")
return options
def change_mac(interface,new_mac):
cmd1 = "ifconfig " + interface + " down"
cmd2 = "ifconfig " + interface + " hw" + " ether " + new_mac
cmd3 = "ifconfig " + interface + " up"
root_password = getpass.getpass("Enter Sudo password : ")
print(f"[+] Changing MAC address for " + interface + " to " + new_mac)
subprocess.call('echo {} | sudo -S {}'.format(root_password,cmd1),shell=True)
subprocess.call('echo {} | sudo -S {}'.format(root_password,cmd2),cmd3),shell=True)
options = get_arguments()
change_mac(options.interface,options.new_mac)
弄清楚了,看起来文档提供了足够的信息来回答我的问题,以及有关 Stack Overflow 上的一些非主题的linux-cli答案。伟大的社区!
〜编辑〜 似乎有一种更好的方法来捕获sudo密码,该密码将使用getpass库并在cli中传递参数来以明文形式显示