2013-04-06 104 views
1

美好的一天。Python輸入密碼並與暗號密碼數據庫比較

我試着寫一個Python腳本,將捕獲的密碼,然後比較其 到系統陰影密碼。

我使用Ubuntu 12.10進行此測試。並以sudo的方式運行腳本。

def login(user, password): 
    "Check if user would be able to login using password" 
    try: 
     pw1 = spwd.getspnam(user)[1] 
     allus = spwd.getspall() 
     print pw1 
     # pw2 = crypt.crypt(password, pw1[:2]) 
     pw2 = crypt.crypt(password, '\$6\$SALTsalt\$') 
     print pw2 
     return pw1 == pw2 
    except KeyError: 
     return 0 # no such user 

現在上面回報

2 diferent密碼,但我得到從陰影的一個。

所以我的問題是如何加密提供的密碼,所以我可以把它比作一個 retreived。任何幫助將是要命

編輯插件

def login(user, password): 
"Check if user would be able to login using password" 
try: 
    pw1 = spwd.getspnam(user)[1] 
    allus = spwd.getspall() 
    #  print allus 
    print pw1 
    #  pw2 = crypt.crypt(password, pw1[:2]) 
    # pw2 = crypt.crypt(password, '\$6\$SALTsalt\$') 
pw2 =hashlib.new() 
pw2.update(password) 
pw2.digest() 

    print pw2 
    return pw1 == pw2 
except KeyError: 
    return 0 # no such user 

這也沒有工作 怎樣才能impliment的haslib獲得哈希匹配系統密碼

+2

什麼是''\ $ 6''?它看起來像破碎的awk代碼,絕對不是有用的Python。 – msw 2013-04-06 04:21:24

+0

我從另一個網站獲得的6美元收入表明它對於我認爲的sha-512有一定的幫助。頁面關閉,所以我可以查找。你知道一個不同的方式 – SAShapeShifter 2013-04-06 04:25:16

+0

地穴只使用DES,它是舊的,而不是在Ubuntu中使用。相反,請查看http://docs.python.org/2/library/hashlib.html。 – msw 2013-04-06 04:29:01

回答

2

我如何做出了表率使用陰影密碼進行身份驗證。我添加了一些評論,讓代碼自己說話。

一些額外的信息:

還要注意(從隱窩模塊文檔):

這個模塊實現的interfac e到crypt(3)例程,這是基於修改的DES算法的單向散列函數;有關更多詳細信息,請參閱Unix手冊頁。可能的用途包括允許Python腳本接受用戶輸入的密碼,或試圖用字典破解Unix密碼。

請注意,此模塊的行爲取決於正在運行的系統中crypt(3)例程的實際實現。因此,當前實現的任何可用擴展也將在此模塊上提供。

這也是爲什麼你不能使用hashlib沒有問題。

import crypt # Interface to crypt(3), to encrypt passwords. 
import getpass # To get a password from user input. 
import spwd # Shadow password database (to read /etc/shadow). 

def login(user, password): 
    """Tries to authenticate a user. 
    Returns True if the authentication succeeds, else the reason 
    (string) is returned.""" 
    try: 
     enc_pwd = spwd.getspnam(user)[1] 
     if enc_pwd in ["NP", "!", "", None]: 
      return "user '%s' has no password set" % user 
     if enc_pwd in ["LK", "*"]: 
      return "account is locked" 
     if enc_pwd == "!!": 
      return "password has expired" 
     # Encryption happens here, the hash is stripped from the 
     # enc_pwd and the algorithm id and salt are used to encrypt 
     # the password. 
     if crypt.crypt(password, enc_pwd) == enc_pwd: 
      return True 
     else: 
      return "incorrect password" 
    except KeyError: 
     return "user '%s' not found" % user 
    return "unknown error" 

if __name__ == "__main__": 
    username = raw_input("Username:") 
    password = getpass.getpass() 
    status = login(username, password) 
    if status == True: 
     print("Logged in!") 
    else: 
     print("Login failed, %s." % status) 
+1

非常感謝,非常好。 它像你一樣,使學習新語言很好。 – SAShapeShifter 2013-04-08 05:01:27

相關問題