Continue lesson 1after we have written the function to change the MAC address on the terminal. We need to check whether the current MAC matches the MAC address specified by the user or not.
Join the channel Telegram belong to AnonyViet 👉 Link 👈 |
To do that, first, we must get the result of the “ifconfig” command and assign it to a string variable. Then, we will find the MAC in that pile of data.
Get the results of the ifconfig command
In module subprocess there is a function called check_output
this function will test your command and possibly assign the result to another variable.
decode('utf-8')
After successfully getting the results of the ifconfig command, we will find the MAC in this pile of data.
FIND MAC
In programming, there is an algorithm called Regular Expressions also known as RegEx for short. RegEX is a regular expression used for advanced string processing through its own expressions. These expressions will have their own rules and you must follow those rules for your expression to work. .
You guys come in Pythex So you can test this algorithm online. Click on the text Regular expressions cheatsheet to learn more about the expressions available in Pythex.
You copy the text that the ifconfig command returns and paste it in place Your test string. On section Your regular expression then enter \w\w:\w\w:\w\w:\w\w:\w\w:\w\w
Ta da! We have found MAC's location, isn't it easy?
Using RegEx in python
The RegEx algorithm is included in the module re of python. We use functions re.search("cú pháp", biến)
Now we add an if statement to check whether the interface's MAC can be read or not.
When the program cannot read the MAC of the interface.
Compact code
We will put in the code from before hàm get_current_mac()
and return the result to the current_mac variable, then print it out. Because curret_mac is a Non-type, I just forced it to a string.
Check MAC
After getting the current MAC address, we will compare it with the new MAC address specified by the user. To see if when changing MAC, the current MAC address is the same as the MAC address the user entered. If they are the same, they will succeed, if they are different, they will fail.
And this is when you enter the wrong interface.
Remember the error of not being able to change MAC when the first pair of numbers is an odd number? Last time the error still appeared, but this time it's gone.