Как узнать имя пользователя windows python

How to get Users of Windows/Linux Systems using Python?

Hello Geek! In this article, we will use Python to get the current users on the Windows and Linux Systems.

The method that we are going to use to get the current users is users(). It is defined in the psutil Library. Therefore syntax of the function will be

syntax: psutil.users()

The function psutil.users() returns all the users that are connected to the System. It returns the users as a list of named tuples.

Each tuple has the name, terminal, host, started and pid as its attributes. The attribute name gives us the username.

PROGRAM

First, import the psutil Python Library to access the users() method.

Now, use the method psutil.users() method to get the list of users as a named tuple and assign to the variable user_list.

Implement a print statement to display that we are going to print the usernames of the users associated with the System.

Iterate over the list of users using a for a statement as the variable user.

Now, under the for loop, we can get the username from the named tuple as user.name and assign it to the variable username.

Now, print the variable username using a print statement.

user_list = psutil.users() print("Users associated with this System are :") for user in user_list: username = user.name print(username)

Output

Users associated with this System are : Guthas

Hurrah! We have successfully obtained the username of all the users associated with the System using simple lines of code in Python.

Thank you for reading this article. I hope this article helped you in some way. Also do check out our other related articles below:

Источник

Full name of Windows user name (in Domain) using Python

I want to retrieve the full name of a Windows computer user in Python. I have found the equivalent batch command:

net user "%USERNAME%" /domain | FIND /I "Full Name" 

that returns the full name (e.g. Full Name John Doe ). I have done the following way by using subprocess but I am wondering if there is a more native way to do it with some Python modules.

import getpass import subprocess import re username = getpass.getuser() p = subprocess.Popen( 'net user %s /domain' % username, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) info, err = p.stdout.read(), p.stderr.read() full_name = re.findall(r'Full Name\s+(.*\S)', info) print(full_name) 

2 Answers 2

The more direct way to do this is to query Active Directory. You’d perform a lookup on the user, followed by getting the displayName attribute. (This maps to the Full Name displayed in Windows.)

You have two options here:

Using a Python AD library, e.g. pyad

This is very Windows-specific, and requires the pywin32 library. It relies on ADSI APIs, so it will only works on Windows.

from pyad import aduser user = aduser.ADUser.from_cn(username) print(user.get_attribute("displayName")) 

How you get the username is up to you. You can use getpass.getuser() , os.environ[«USERNAME»] (Windows-only), etc.

Using a Python LDAP library, e.g. ldap3

This follows the standard LDAP protocol, with a pure Python implementation, so should work from any client OS.

Using raw LDAP queries is rather more involved than the ADSI abstractions. I suggest you read the documentation (which has decent tutorials) and search for more tutorials on interacting with Microsoft AD via ldap3 .

Note that one possible issue is that searching by username (CN) alone might get you the wrong object. It’s possible to have multiple objects with the same CN across multiple OUs. If you want to be more precise, you might want to use a unique identifier like the SID.

Источник

Get Username in Python using os module

To get the current username in Python, the easiest way is with the os module getlogin() function.

import os print(os.getlogin()) #Output: The Programming Expert

Another way you can get the current username is from the dictionary of environment variables of the operating system.

import os print(os.environ.get("USERNAME")) #Output: The Programming Expert

One other way you can get the username is with the os module path.expanduser() function.

import os print(os.path.expanduser("~")) #Output: C:\Users\The Programming Expert

In Python, the os module provides us with many useful functions which allow us to get information about the operating system and environment we are working with.

One piece of information which can be valuable is the current logged in user and the username of that user.

There are a few ways you can get the current username in Python.

The easiest way to get the name of the current user in Python is with the os module getlogin() function.

Below shows a simple example of using getlogin() to get the current username in Python.

import os print(os.getlogin()) #Output: The Programming Expert

Another way you can get the current username is from the dictionary of environment variables of the operating system.

You can access the dictionary of environment variables with the environ dictionary.

Then, to get the username, use get() to get the username value.

Below shows you how to use the dictionary of environment variables to get the username in Python.

import os print(os.environ.get("USERNAME")) #Output: The Programming Expert

One other way you can get the username is with the os module path.expanduser() function.

You can use this method if you want to get the root of the user path.

Below shows you how to use path.expanduser() to get the username in Python.

import os print(os.path.expanduser("~")) #Output: C:\Users\The Programming Expert

Hopefully this article has been useful for you to get the current username in Python.

  • 1. Using Python to Check if Deque is Empty
  • 2. Using Python to Convert Decimal to String
  • 3. Using Lambda Expression with min() in Python
  • 4. Change Python Turtle Background Color with screensize() Function
  • 5. Python Check if Attribute Exists in Object with hasattr() Function
  • 6. pandas Standard Deviation – Using std() to Find Standard Deviation
  • 7. math gcd Python – Find Greatest Common Divisor with math.gcd() Function
  • 8. Get Month Name from Datetime in pandas DataFrame
  • 9. How to Check if Number is Negative in Python
  • 10. Get Day Name from Datetime in pandas DataFrame

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Python: как получить имя пользователя компьютера

Имя пользователя компьютера — это уникальное имя, присвоенное пользователю операционной системы. Python предоставляет простые и эффективные способы получить имя пользователя компьютера.

Модуль «os»

Модуль «os» в Python предоставляет функцию getlogin() , которая возвращает имя пользователя, залогинившегося в операционной системе. Эта функция доступна для большинства операционных систем, таких как Windows, macOS и Linux. Пример использования:

import os username = os.getlogin() print(username) 

Код выше вернет имя пользователя, залогинившегося в операционной системе.

Модуль «getpass»

Модуль «getpass» в Python предоставляет функцию getuser() , которая возвращает имя пользователя, под которым был запущен скрипт. Это может быть полезно, если вы хотите получить имя пользователя, выполняющего текущий скрипт, независимо от того, залогинен пользователь в операционной системе или нет. Пример использования:

import getpass username = getpass.getuser() print(username) 

Код выше вернет имя пользователя, под которым был запущен скрипт.

Заключение

Python предоставляет удобные способы получить имя пользователя компьютера с использованием модулей «os» и «getpass». Выбор подходящего метода зависит от вашего конкретного случая использования. Имя пользователя компьютера может быть полезно для создания персонализированного опыта пользователя или для работы с файлами и директориями, специфичными для конкретного пользователя.

Источник

Читайте также:  Scaling an image with javascript
Оцените статью