import os
import subprocess
import sys

def alert(arg): 
   sys.stderr.write("%d%d%d" % (arg, arg, arg))

new_admin = []
new_domain_admin = []

def ecmd(command,filename,group):
	cmd = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
	res,err = cmd.communicate()
	if err:
		print(err)
	else:
		val = res.replace("The command completed successfully.","").strip()
		keyword = "-------------------------------------------------------------------------------"
		before_keyword, keyword, after_keyword = val.partition(keyword)
		if command == 'net localgroup administrators' :
			admin = (after_keyword.strip().split("\n"))
			paths = "C:\\ProgramData\\"+filename
			if  os.path.exists(paths):
			    f = open(paths, "r")
			    v = (f.read())
			    f.close()
			    for i in admin:
			    	if i.strip() in v:
			    		pass
			    	else:
					    w = open(paths,"a")
					    w.write("\n"+i.strip())
					    w.close()
					    new_admin.append(i.strip())
					   
			else:
				file1 = open(paths, "w+")
				for i in admin:
					file1.write("\n"+i.strip())
				file1.close()
			
		else:
			admin = (after_keyword.strip().split())
			paths = "C:\\ProgramData\\"+filename

			if  os.path.exists(paths):
			    f = open(paths, "r")
			    v = (f.read())
			    f.close()
			    for i in admin:
			    	if i.strip() in v:
			    		pass
			    	else:
					    w = open(paths,"a")
					    w.write("\n"+i.strip())
					    w.close()
					    new_domain_admin.append(i.strip())
					    
			else:
				file1 = open(paths, "w+")
				for i in admin:
					file1.write("\n"+i.strip())
				file1.close()

ecmd('net localgroup administrators','Admin_list.txt','Administrator Group')
ecmd('net group "Domain Admins" /DOMAIN','Domain Admin List.txt','Domain Admins Group')
if len(new_admin) > 0 and len(new_domain_admin) > 0:
	for i in new_admin:
		print(i+" "+" is the new user added to Administrators Group")
	for j in new_domain_admin:
		print(j+" "+" is the new user added to Domain Admins Group")
	alert(1)
elif len(new_admin) > 0 and len(new_domain_admin) == 0:
	for i in new_admin:
		print(i+" "+" is the new user added to Administrators Group")
	alert(1)
elif len(new_admin) == 0 and len(new_domain_admin) > 0:
	for i in new_domain_admin:
		print(i+" "+" is the new user added to Domain Admins Group")
	alert(1)
else:
	print("No New users added ")
	alert(0)

del new_admin [:]
del new_domain_admin [:]