1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Use subprocess and pamtester to check if username and password match. pamtester needs to be executed with administrator authority. subprocess と pamtester を使用してユーザー名とパスワードが合致するか調べる pamtester は管理者権限で実行する必要が有る """ import os, pwd import subprocess # See: https://qiita.com/quenhulu/items/61edc5dffa711b08d64c def getuser(): """Get the username from the environment or password database. First try various environment variables, then the password database. This works on Windows as long as USERNAME is set. """ for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'): user = os.environ.get(name) if user: return user # If this fails, the exception will "explain" why return pwd.getpwuid(os.getuid())[0] # @return: dictionary def execCmd(cmd, outText = ""): commandName = cmd.split(" ", 2)[0] ps = subprocess.Popen("/usr/bin/which '%s'" % commandName, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = ps.communicate() if ps.returncode != 0: raise Exception("execCmd: Command not found on PATH: %s" % commandName) ps = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) if outText == "": stdout, stderr = ps.communicate() else: stdout, stderr = ps.communicate(input=outText.encode()) return {"returncode": ps.returncode, "stdout": stdout.decode('utf-8').strip(), "stderr": stderr.decode('utf-8').strip()} def isMatchedUsernameAndPass(username, password): try: # ret = execCmd("sudo pamtester auth %s authenticate" % username, password) ret = execCmd("pamtester auth %s authenticate" % username, password) if ret["returncode"] == 0: print("Success") return True else: print("Failure") return False return ret except: print("Error") return False if __name__ == '__main__': you = getuser() if you != 'root': print("Needs to be executed with administrator authority. you are %s." % you) exit(1) ret = isMatchedUsernameAndPass("USERNAME", "PASSWORD") print(ret) |