Skip to content

Instantly share code, notes, and snippets.

@RDCH106
Last active February 10, 2021 10:55
Show Gist options
  • Save RDCH106/fdd419ef7dd803932b16056aab1d2300 to your computer and use it in GitHub Desktop.
Save RDCH106/fdd419ef7dd803932b16056aab1d2300 to your computer and use it in GitHub Desktop.
Cross-platform script to check admin rights in Python
import ctypes, os
from sys import exit
def is_admin():
is_admin = False
is_win = False
try:
is_admin = os.getuid() == 0
except AttributeError:
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
is_win = True
print ("Admin privileges: {}".format(is_admin))
return is_admin, is_win
if __name__ == "__main__":
is_admin, is_win = is_admin()
# Converting boolean to integer
ret = int(is_admin == False)
if is_win:
exit(ret)
else:
exit(ret * -1)
#!/bin/bash
pwd
cd `dirname $0`
SCRIPTDIR=`pwd`
pwd
python is_admin.py
if [ $? -eq 0 ]
then
# [your_executable]
else
echo Exit Code is $?
echo.
echo Admin privileges required
echo Run it again as Administrator
echo.
read -rsp $'Press any key to continue...\n' -n 1 key
exit $?
fi
read -rsp $'Press any key to continue...\n' -n 1 key
@echo off
cd
cd /D "%~dp0"
cd
python is_admin.py
if errorlevel 1 (
echo Exit Code is %errorlevel%
echo.
echo Admin privileges required
echo Run it again as Administrator
echo.
pause
exit /b %errorlevel%
)
#REM [your_executable].exe
pause
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment