Skip to content

Commit a2bbd2d

Browse files
committed
make more robust code
1 parent cb57b31 commit a2bbd2d

1 file changed

Lines changed: 87 additions & 8 deletions

File tree

projects/WindowsSystemOps/Account/windows-user-accounts-manager.py

Lines changed: 87 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"""
44
Created by PyCharm.
55
File Name: LinuxBashShellScriptForOps:windows-user-accounts-manager.py
6-
Version: 0.0.2
6+
Version: 0.0.3
77
Author: dgden
88
Author Email: dgdenterprise@gmail.com
99
URL: https://github.com/DingGuodong/LinuxBashShellScriptForOps
@@ -34,14 +34,14 @@
3434
Notes:
3535
"""
3636
import json
37+
import time
38+
import warnings
39+
from base64 import b64encode
3740
from itertools import product
3841
from multiprocessing import Pool
3942

4043
import requests
41-
import time
42-
import warnings
4344
import winrm
44-
from base64 import b64encode
4545
from winrm.protocol import Protocol
4646

4747
# disable python warnings
@@ -336,6 +336,8 @@ def query_account_status(server, name):
336336
script = '(NET USER {name} | where {{$_ -match "帐户启用*"}}).Split()|select -Last 1'.format(name=name)
337337
status_code, std_out, std_err = run_powershell_with_codepage_936(ip, user, psw, script)
338338
if status_code != 0:
339+
script = '[bool](((NET USER {name}) -match "帐户启用") -match "no")'.format(name=name)
340+
status_code, std_out, std_err = run_powershell_with_codepage_936(ip, user, psw, script)
339341
# print(std_out.strip())
340342
# print(std_err.strip())
341343
# if std_out in "requests failed.":
@@ -355,25 +357,102 @@ def query_account_status(server, name):
355357
return status in ["Yes", "True"]
356358

357359

360+
def query_account_status_u1(server, name):
361+
"""
362+
query user account status and return (account_status, message)
363+
status meaning:
364+
None: error, see message
365+
True: enabled
366+
False: disabled
367+
:param server:hostname or ip address
368+
:type server:str | int
369+
:param name: user account name
370+
:type name:str
371+
:return:tuple
372+
:rtype:tuple
373+
"""
374+
ip, user, psw = get_acc_psw_with_ends(server)
375+
if BIZ_USERNAME_PREFIX not in name:
376+
name = BIZ_USERNAME_PREFIX + name
377+
script = '(Get-LocalUser -Name {name}).Enabled'.format(name=name)
378+
status_code, std_out, std_err = run_powershell(ip, user, psw, script)
379+
# $LastExitCode maybe 1, 2, etc, so do NOT use `status_code == 1`
380+
if status_code != 0: # some reason: powershell version < 5.0
381+
# -Split (NET USER guest | where {$_ -match "帐户启用*"})| select -Last 1
382+
# (NET USER guest | where {$_ -match "帐户启用*"}).Split()[-1]
383+
# (NET USER guest | where {$_ -match "帐户启用*"}).Split()|select -Last 1
384+
# [bool]([regex]::Match(((NET USER guest) -match "帐户启用"),'Yes')).Success
385+
# [bool](((NET USER guest) -match "帐户启用") -match "no")
386+
script = '(NET USER {name} | where {{$_ -match "帐户启用*"}}).Split()|select -Last 1'.format(name=name)
387+
status_code, std_out, std_err = run_powershell_with_codepage_936(ip, user, psw, script)
388+
if status_code != 0:
389+
# print(std_out.strip())
390+
# print(std_err.strip())
391+
# if std_out in "requests failed.":
392+
# print("WARN: account {} in IP {} may has an issue, "
393+
# "such as `requests.exceptions.ConnectionError`, "
394+
# u"error detail: {}.".format(name, ip, std_err.decode('gbk')))
395+
if "ConnectionError" in std_err:
396+
print("WARN: account {} in IP {} may has an issue, "
397+
"such as `requests.exceptions.ConnectionError`, "
398+
u"error detail: {}.".format(name, ip, std_err.decode('gbk')))
399+
return None, std_err.st
400+
401+
message = std_out.strip()
402+
if message == "":
403+
message = "NotExist"
404+
405+
account_status = message in ["Yes", "True"]
406+
# print("account {name}'s status on {server} is {status}.".format(name=name, status=status, server=server))
407+
return account_status, message
408+
409+
358410
def main_change_account_status(ip=250, user='kurt'):
359411
print("exec time: {}".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
360412
is_account_enabled = query_account_status(ip, user)
361-
if is_account_enabled:
413+
if is_account_enabled is True:
362414
# 如果已经被启用,则禁用
363415
print("disabling account {name} on {server}".format(name=user, server=ip))
364416
disable_account(ip, user)
365-
else:
417+
elif is_account_enabled is False:
366418
# 如果已经被禁用,则启用
367419
print("enabling account {name} on {server}".format(name=user, server=ip))
368420
enable_account(ip, user)
421+
else:
422+
print("status is strange, we should better verify it manually")
369423

370424
account_status = query_account_status(ip, user)
371-
if account_status:
425+
if account_status is None:
426+
print("status is strange, we should better verify it manually")
427+
elif account_status is True:
372428
print("account {name} on {server} is enabled.".format(name=user, server=ip))
373429
else:
374430
print("account {name} on {server} is disabled.".format(name=user, server=ip))
375431

376432

433+
def main_change_account_status_u1(ip=250, user='kurt'):
434+
import sys
435+
print("exec time: {}".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
436+
is_account_enabled, message = query_account_status_u1(ip, user)
437+
if is_account_enabled is True:
438+
# 如果已经被启用,则禁用
439+
print("disabling account {name} on {server}".format(name=user, server=ip))
440+
disable_account(ip, user)
441+
account_status, message = query_account_status_u1(ip, user)
442+
if account_status is False:
443+
print("account {name} on {server} is disabled.".format(name=user, server=ip))
444+
elif is_account_enabled is False:
445+
# 如果已经被禁用,则启用
446+
print("enabling account {name} on {server}".format(name=user, server=ip))
447+
enable_account(ip, user)
448+
account_status, message = query_account_status_u1(ip, user)
449+
if account_status is True:
450+
print("account {name} on {server} is enabled.".format(name=user, server=ip))
451+
else:
452+
print("status is strange, we should better verify it manually, message is: {msg}".format(msg=message))
453+
sys.exit(2)
454+
455+
377456
def __main_disable_all_account():
378457
# deprecated
379458
if servers is not None:
@@ -435,5 +514,5 @@ def main_disable_all_account():
435514

436515
if __name__ == '__main__':
437516
main_disable_all_account()
438-
# main_enable_account(147, 'username')
517+
# main_change_account_status_u1(147, 'username')
439518
# print get_user_logged_on_server(104, 'username')

0 commit comments

Comments
 (0)