Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import os
  4.  
  5. display_env = 'DISPLAY='
  6. dbus_env = 'DBUS_SESSION_BUS_ADDRESS='
  7. user_env = 'USER='
  8.  
  9.  
  10. def re_pid_environ(pid):
  11. """
  12. read environ of 1 process
  13. returns tuple with USER, DBUS, DISPLAY like follow:
  14. ('user', 'DISPLAY=:0',
  15. 'DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus')
  16. returns None if these vars is not in /proc/[pid]/environ
  17. """
  18.  
  19. try:
  20. with open('/proc/' + pid + '/environ', 'rb') as f:
  21. env = f.read().decode('utf-8', 'ignore')
  22. except FileNotFoundError:
  23. return None
  24. except ProcessLookupError:
  25. return None
  26.  
  27. if display_env in env and dbus_env in env and user_env in env:
  28.  
  29. env_list = env.split('\x00')
  30.  
  31. print(pid, env_list, '\n')
  32.  
  33. # iterating over a list of process environment variables
  34. for i in env_list:
  35.  
  36. # exclude Display Manager's user
  37. if i.startswith('HOME=/var'):
  38. return None
  39.  
  40. if i.startswith(user_env):
  41. user = i
  42. if user == 'USER=root':
  43. return None
  44. continue
  45.  
  46. if i.startswith(display_env):
  47. display = i[:10]
  48. continue
  49.  
  50. if i.startswith(dbus_env):
  51. dbus = i
  52. continue
  53.  
  54. try:
  55. return user.partition('USER=')[2], display, dbus
  56. except UnboundLocalError:
  57. return None
  58.  
  59.  
  60. def root_notify_env():
  61. """return set(user, display, dbus)"""
  62. unsorted_envs_list = []
  63. # iterates over processes, find processes with suitable env
  64. for pid in os.listdir('/proc'):
  65.  
  66. # os.path.exists('/proc/[pid]/exe') indicates process existanse
  67. if os.path.exists('/proc/' + pid + '/exe') is True:
  68. one_env = re_pid_environ(pid)
  69. unsorted_envs_list.append(one_env)
  70.  
  71. env = set(unsorted_envs_list)
  72. env.discard(None)
  73.  
  74. # deduplicate dbus
  75. new_env = []
  76. end = []
  77. for i in env:
  78. key = i[0] + i[1]
  79. if key not in end:
  80. end.append(key)
  81. new_env.append(i)
  82. else:
  83. continue
  84.  
  85. return new_env
  86.  
  87.  
  88. print(root_notify_env())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement