usermgr.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # Copyright (C) 2010 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. '''
  16. This file implements user management program. The user name and
  17. its password is appended in csv file.
  18. '''
  19. import random
  20. from hashlib import sha1
  21. import csv
  22. import getpass
  23. import getopt
  24. import sys
  25. VERSION_NUMBER = 'bind10'
  26. DEFAULT_FILE = 'passwd.csv'
  27. def gen_password_hash(password):
  28. salt = "".join(chr(random.randint(33, 127)) for x in range(64))
  29. saltedpwd = sha1((password + salt).encode()).hexdigest()
  30. return salt, saltedpwd
  31. def username_exist(name, filename):
  32. # The file may doesn't exist.
  33. exist = False
  34. csvfile = None
  35. try:
  36. csvfile = open(filename)
  37. reader = csv.reader(csvfile)
  38. for row in reader:
  39. if name == row[0]:
  40. exist = True
  41. break
  42. except Exception:
  43. pass
  44. if csvfile:
  45. csvfile.close()
  46. return exist
  47. def save_userinfo(username, pw, salt, filename):
  48. csvfile = open(filename, 'a')
  49. writer = csv.writer(csvfile)
  50. writer.writerow([username, pw, salt])
  51. csvfile.close()
  52. print("add user success!")
  53. def usage():
  54. print('''Usage: usermgr [options]
  55. -h, --help \t Show this help message and exit
  56. -f, --file \t Specify the file to append user name and password
  57. -v, --version\t Get version number
  58. ''')
  59. def main():
  60. filename = DEFAULT_FILE
  61. try:
  62. opts, args = getopt.getopt(sys.argv[1:], 'hvf:',
  63. ['help', 'file=', 'version='])
  64. except getopt.GetoptError as err:
  65. print(err)
  66. usage()
  67. sys.exit(2)
  68. for op, param in opts:
  69. if op in ('-h', '--help'):
  70. usage()
  71. sys.exit()
  72. elif op in ('-v', '--version'):
  73. print(VERSION_NUMBER)
  74. sys.exit()
  75. elif op in ('-f', "--file"):
  76. filename = param
  77. else:
  78. assert False, 'unknown option'
  79. usage()
  80. try:
  81. while True :
  82. name = input("Desired Login Name:")
  83. if username_exist(name, filename):
  84. print("The usename already exist!")
  85. continue
  86. while True:
  87. pwd1 = getpass.getpass("Choose a password:")
  88. pwd2 = getpass.getpass("Re-enter password:")
  89. if pwd1 != pwd2:
  90. print("password is not same, please input again")
  91. else:
  92. break;
  93. salt, pw = gen_password_hash(pwd1)
  94. save_userinfo(name, pw, salt, filename)
  95. inputdata = input('continue by input \'y\' or \'Y\':')
  96. if inputdata not in ['y', 'Y']:
  97. break
  98. except KeyboardInterrupt:
  99. pass
  100. if __name__ == '__main__':
  101. main()