check_user.py


SUBMITTED BY: Header

DATE: April 6, 2022, 4:36 p.m.

FORMAT: Text only

SIZE: 2.0 kB

HITS: 268

  1. import os
  2. import sys
  3. import typing as t
  4. from datetime import datetime
  5. from flask import Flask, jsonify
  6. app = Flask(__name__)
  7. app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
  8. app.config['JSON_SORT_KEYS'] = False
  9. def count_connection(username: str) -> int:
  10. command = 'ps -u %s' % username
  11. result = os.popen(command).readlines()
  12. return len([line for line in result if 'sshd' in line])
  13. def get_expiration_date(username: str) -> t.Optional[str]:
  14. command = 'chage -l %s' % username
  15. result = os.popen(command).readlines()
  16. for line in result:
  17. line = list(map(str.strip, line.split(':')))
  18. if line[0].lower() == 'account expires' and line[1] != 'never':
  19. return datetime.strptime(line[1], '%b %d, %Y').strftime('%d/%m/%Y')
  20. return None
  21. def get_expiration_days(date: str) -> int:
  22. if not isinstance(date, str) or date.lower() == 'never' or not isinstance(date, str):
  23. return -1
  24. return (datetime.strptime(date, '%d/%m/%Y') - datetime.now()).days
  25. def get_time_online(username: str) -> t.Optional[str]:
  26. command = 'ps -u %s -o etime --no-headers' % username
  27. result = os.popen(command).readlines()
  28. return result[0].strip() if result else None
  29. @app.route('/check/<string:username>')
  30. def check_user(username):
  31. try:
  32. count = count_connection(username)
  33. expiration_date = get_expiration_date(username)
  34. return jsonify(
  35. {
  36. 'username': username,
  37. 'count_connection': count,
  38. 'expiration_date': expiration_date,
  39. 'expiration_days': get_expiration_days(expiration_date),
  40. 'time_online': get_time_online(username),
  41. }
  42. )
  43. except Exception as e:
  44. return jsonify({'error': str(e)})
  45. if __name__ == '__main__':
  46. app.run(
  47. host='0.0.0.0',
  48. port=int(sys.argv[1]) if len(sys.argv) > 1 else 2095,
  49. )

comments powered by Disqus