Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get admin rights to write Windows usernames in a csv file with Python?

Tags:

python

uac

rdp

I want to write Windows usernames in a csv file. I wrote this script in Linux, connected to Win10 PC via krdc and RDP protocol. I shared my Linux drive over that remote desktop app with Win10 and then I ran this scipt from that shared disk in Win10.

If I do this via command prompt as administrator it runs as expected. However, if I run it as a normal user and UAC is confirmed as Yes, the output file is not created.

How to run this script as a normal user, answering yes to UAC and having that file writen in my mounted drive over rdp protocol in krdc remote app where Win10 sees that drive as \\TSCLIENT?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import ctypes
import sys
import subprocess


def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    subprocess.call(['wmic', '/output:usracc.txt', 'useraccount', 'list', 'full', '/format:csv'])
else:
    # Re-run the program with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
like image 492
Hrvoje T Avatar asked Mar 27 '18 05:03

Hrvoje T


1 Answers

If you want to do this with out having administrator privileges you can:

import os
import csv

userList = os.popen("net user").read().split()[5:-4]

outFile = open("userList.csv", 'w')
with outFile:
    fileWriter = csv.writer(outFile)

for user in userList:
    print(user)
    fileWriter.writerow([user]) 

That code will give you a file "userList.csv" with all the users without being an administrator

like image 82
Ricardo Avatar answered Oct 20 '22 01:10

Ricardo