shreddinghost
shreddinghost

Reputation: 33

How to handle accent marks in WiFi names?

I made a code that returns all the WiFi names and passwords in your device. Since my device's language is Spanish, the cmd output has accent marks and python can't decode it. I want to know how to eliminate the accent marks or just use a different encoding.

import subprocess
import re
import unicodedata

command_output=subprocess.run(['netsh','wlan','show','profiles'],capture_output=True).stdout.decode()
profile_names=re.findall("Perfil de todos los usuarios     : (.*)\r", command_output)
wifi_list=[]

if len(profile_names) !=0:
    for red in profile_names:
        wifi_profile={}
        profile_info=subprocess.run(['netsh','wlan','show','profiles',red], capture_output=True).stdout.decode()

        if re.search("Clave de seguridad                         : Ausente", profile_info):
            continue
        else:
            wifi_profile["ssid"]=red
            profile_info_pass=subprocess.run(["netsh","wlan","show","profile",red,"key=clear"])
            password=re.search("Contenido de la clave  : (.*)\r")

            if password==None:
                wifi_profile["password"]=None
            else:
                wifi_profile["password"]=password[1]
            wifi_list.append(wifi_profile)
for x in range(len(wifi_list)):
    print(wifi_list[x])

The error I get is:

File "getwifi.py", line 11, in <module>
    profile_info=subprocess.run(['netsh','wlan','show','profiles',red], capture_output=True).stdout.decode()
  UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa2 in position 179: invalid start byte

Upvotes: 1

Views: 212

Answers (1)

chepner
chepner

Reputation: 531075

By default, Python assumes that the bytes value is UTF-8-encoded. You can either pass the correct encoding (I'll assume it's iso8859 here) to decode:

profile_info = subprocess.run(['netsh','wlan','show','profiles',red],
                               capture_output=True).stdout.decode("iso8859")

or you can tell subprocess.run to decode it for you with the encoding argument.

profile_info = subprocess.run(['netsh','wlan','show','profiles',red],
                               capture_output=True, encoding="iso8859").stdout

A third option (beyond the scope of this answer) would be to configure your environment to make sure that netsh outputs UTF-8-encoded output in the first place.

Upvotes: 3

Related Questions