Home My First Python Script
Post
Cancel

My First Python Script

Intro

My Python is like my Spanglish, I can just about read it and writing it is even worse!

So I’ve just started the below linked course on Udemy. Like the instructor I believe that the best way to learn is to be hands on

MAC Address Changer

The mini project the course starts off with is a MAC address changer.

Within it you learn the following

  • Print statements
  • Importing modules
  • Using subprocess.call from module subprocess to initiate system commands.
  • Parsing arguments.
  • Defining functions.
  • Creating statements.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python

import subprocess
import optparse

def get_arguments():
    parser = optparse.OptionParser()
    parser.add_option("-i", "--interface", dest="interface", help="Interface to change its MAC address")
    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, use --help for more info.")
    elif not options.new_mac:
        parser.error("[-] Please specify a new MAC address, use --help for more info.")
    return options

def change_mac(interface, new_mac):
    print("[+] Changing MAC Address for " + interface + " to " + new_mac)
    subprocess.call(["ifconfig", interface, "down"])
    subprocess.call(["ifconfig", interface, "hw", "ether", new_mac])
    subprocess.call(["ifconfig", interface, "up"])

options = get_arguments()
change_mac(options.interface, options.new_mac)
This post is licensed under CC BY 4.0 by the author.