2014-01-06 71 views
0

我目前處於軟件開發學位的第三年,我正在考慮在明年推出一些安全模塊,我選擇了「Violent Python「作爲介紹並學習一種新語言,但是我被困在第一個練習中。Python For Loop僅循環一次(對於文本文件中的每一行)

我不是新手,編程,也許我只是累了 - 它已經在小睡一整天 - 但這種簡單的腳本不會工作:

import crypt 
def testPass(cryptPass): 
salt = cryptPass[0:2] 
dictFile = open('dictionary.txt') 
for word in dictFile.readlines(): 
    word = word.strip('\n') 
    print "[*] Attempting password: "+word+"\n" 
    cryptWord = crypt.crypt(word,salt) 
    if (cryptWord == cryptPass): 
    print "[+] Found Password: "+word+"\n" 
    return 
    print "[-] Password Not Found.\n" 
    return 
def main(): 
passFile = open('passwords.txt') 
for line in passFile.readlines(): 
    if ":" in line: 
    user = line.split(':')[0] 
    cryptPass = line.split(':')[1].strip(' ') 
    print "[*] Cracking Password For: "+user 
    testPass(cryptPass) 
if __name__ == "__main__": 
main() 

password.txt的有來自/兩個用戶etc/passwd(受害者和根),並通過它們循環良好。我在我的dictionary.txt三個密碼,並由於某種原因,只嘗試第一個密碼:

[*] Cracking Password For: victim 
[*] Attempting password: break 

[-] Password Not Found. 

[*] Cracking Password For: root 
[*] Attempting password: break 

[-] Password Not Found. 

有人可以解釋爲什麼上面從書中擡起的代碼沒有工作?我設法通過使用「with open」來解決問題:

with open('dictionary.txt') as f: 
for word in f: 
    word = word.strip("\n") 
    cryptWord = crypt.crypt(word,salt) 
    if (cryptWord == cryptPass): 
    print "[+] Found Password: "+word+"\n" 
    return 
    print "[-] Password Not Found.\n" 
    return 
+3

請檢查您的代碼縮進(理想情況下每層4個空格) - 空格在Python中很重要! – jonrsharpe

+0

是的! :-)然後發佈一個dictionary.txt示例 – maurelio79

回答

2

這是一個縮進錯誤。對於事情的正常工作,你的「testPass」功能應該是這樣的:

def testPass(cryptPass): 
    salt = cryptPass[0:2] 
    dictFile = open('dictionary.txt') 
    for word in dictFile.readlines(): 
     word = word.strip('\n') 
     print "[*] Attempting password: "+word+"\n" 
     cryptWord = crypt.crypt(word,salt) 
     if (cryptWord == cryptPass): 
      print "[+] Found Password: "+word+"\n" 
      return 
    print "[-] Password Not Found.\n" 
    return 

這樣的話,它會遍歷字典中的每一個字,並返回一旦發現密碼。如果它循環遍歷所有內容而沒有找到它,則應該,然後打印「未找到密碼」。你的問題是你的代碼(爲了清晰而間隔一點)實際上是這樣縮進的:

def testPass(cryptPass): 
    salt = cryptPass[0:2] 
    dictFile = open('dictionary.txt') 
    for word in dictFile.readlines(): 
     word = word.strip('\n') 
     print "[*] Attempting password: "+word+"\n" 
     cryptWord = crypt.crypt(word,salt) 
     if (cryptWord == cryptPass): 
      print "[+] Found Password: "+word+"\n" 
      return 
     print "[-] Password Not Found.\n" 
     return 

看到區別?像這樣,它只會檢查第一個單詞,因爲第二個「return」在循環中。請驗證您的縮進(理想情況下4個空格,@jonrsharpe說,或一個標籤)並再次嘗試。我懷疑這會解決你的問題。

+1

製表符與空格 - 永恆的聖戰。好答案 :) –