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

In this article we will discuss how to get the current username in python. Method 1 Using OS library getlogin method of OS library is used to get the current username. Syntax os.getlogin In order to use this function we need to import os library first . Example

In this article, we will discuss how to get the current username in python.

Method 1: Using OS library

getlogin() method of OS library is used to get the current username.

Syntax : os.getlogin( ) 

In order to use this function we need to import os library first .

Example 1: getlogin() method

Python3

Output :

'KRISHNA KARTHIKEYA'

Example 2: os.path.expanduser() method 

There is another method available in os library named path.expanduser() method. In this function, we need to pass the Tilde operator within single quotes as an argument.

syntax : os.path.expanduser( ) 

Note: In this method, we need to pass the tilde operator as an argument.

Python3

import os

os.path.expanduser('~')

Output :

'C:\Users\KRISHNA KARTHIKEYA'

Example 3: environ.get() method

This method is also available in the os module. We need to pass USERNAME as an argument into this method. Let us see the syntax and example .

syntax : os.environ.get( ” USERNAME” )

note : In some cases we need pass USER instead of USERNAME . Most of the cases we pass USERNAME as argument .

Python3

import os

os.environ.get('USERNAME')

Output :

'KRISHNA KARTHIKEYA'

Method 2: Using getpass library

In this module, we need to use getuser() method to return the current username. This getuser() method is available in getpass library.

syntax : getpass.getuser( )

Example :

Python3

import getpass as gt

gt.getuser()

Output :

'KRISHNA KARTHIKEYA'

Method 3: Using os and pwd modules

pwd module works only with Linux environment. But os works with both Windows and Linux. This means some methods work with only windows and some methods work with only Linux. If we execute this method in Linux we will get output as root. Let us see the syntax and example of getpwuid() method.

syntax : getpwuid( os.getuid() )[0]

Here [0] is like index. Generally this function returns many outputs like system name , password , uid , bash..etc . Here we need username . It is at index 0 . so we are specifying [0] .

Example  : 

Python3

import os

import pwd

pwd.getpwuid(os.getuid())[0]

Output :

'root'

In this article, we will discuss how to get the current username in python.

Method 1: Using OS library

getlogin() method of OS library is used to get the current username.

Syntax : os.getlogin( ) 

In order to use this function we need to import os library first .

Example 1: getlogin() method

Python3

Output :

'KRISHNA KARTHIKEYA'

Example 2: os.path.expanduser() method 

There is another method available in os library named path.expanduser() method. In this function, we need to pass the Tilde operator within single quotes as an argument.

syntax : os.path.expanduser( ) 

Note: In this method, we need to pass the tilde operator as an argument.

Python3

import os

os.path.expanduser('~')

Output :

'C:\Users\KRISHNA KARTHIKEYA'

Example 3: environ.get() method

This method is also available in the os module. We need to pass USERNAME as an argument into this method. Let us see the syntax and example .

syntax : os.environ.get( ” USERNAME” )

note : In some cases we need pass USER instead of USERNAME . Most of the cases we pass USERNAME as argument .

Python3

import os

os.environ.get('USERNAME')

Output :

'KRISHNA KARTHIKEYA'

Method 2: Using getpass library

In this module, we need to use getuser() method to return the current username. This getuser() method is available in getpass library.

syntax : getpass.getuser( )

Example :

Python3

import getpass as gt

gt.getuser()

Output :

'KRISHNA KARTHIKEYA'

Method 3: Using os and pwd modules

pwd module works only with Linux environment. But os works with both Windows and Linux. This means some methods work with only windows and some methods work with only Linux. If we execute this method in Linux we will get output as root. Let us see the syntax and example of getpwuid() method.

syntax : getpwuid( os.getuid() )[0]

Here [0] is like index. Generally this function returns many outputs like system name , password , uid , bash..etc . Here we need username . It is at index 0 . so we are specifying [0] .

Example  : 

Python3

import os

import pwd

pwd.getpwuid(os.getuid())[0]

Output :

'root'

None of the above worked in my case (scroll down to the actual solution).
The problem I’m getting with all solutions is the wrong username when running commands with sudo:

  • psutil soulution:
$ python3
>>> import psutil
>>> psutil.Process().username()
'ubuntu' # OK!

$ sudo su
$ python3
>>> import psutil
>>> psutil.Process().username()
'root' # OK!

$ sudo python3
>>> import psutil
>>> psutil.Process().username()
'root' # WRONG, should be ubuntu!
  • getpass solution:
$ python3
>>> import getpass
>>> getpass.getuser()
'ubuntu' # OK!

$ sudo su
$ python3
>>> import getpass
>>> getpass.getuser()
'root' # OK!

$ sudo python3
>>> import getpass
>>> getpass.getuser()
'root' # WRONG, should be ubuntu!
  • pwd + os.getuid solution:
$ python3
>>> import os, pwd
>>> pwd.getpwuid( os.getuid() )[ 0 ]
'ubuntu' # OK!

$ sudo su
$ python3
>>> import os, pwd
>>> pwd.getpwuid( os.getuid() )[ 0 ]
'root' # OK!

$ sudo python3
>>> import getpass
>>> getpass.getuser()
'root' # WRONG, should be ubuntu!
  • os.getlogin works a bit different, but still wrong:
$ python3
>>> import os
>>> os.getlogin()
'ubuntu' # OK!

$ sudo su
$ python3
>>> import os
>>> os.getlogin()
'ubuntu' # WRONG, should be root!


$ sudo python3
>>> import os
>>> os.getlogin()
'ubuntu' # OK!
  • os.getenv gives the same results:
$ python3
>>> import os
>>> os.getenv('SUDO_USER', os.getenv('USER'))
'ubuntu' # OK!

$ sudo su
$ python3
>>> import os
>>> os.getenv('SUDO_USER', os.getenv('USER'))
'ubuntu' # WRONG, should be root!


$ sudo python3
>>> import os
>>> os.getenv('SUDO_USER', os.getenv('USER'))
'ubuntu' # OK!

Switching SUDO_USER and USER gives the wrong result in sudo python3 case.

Actual solution (non-portable)

Solution is a bit tricky and rely on the default root home directory location but works for all cases:

$ python3
>>> import os
>>> 'root' if os.path.expanduser('~') == '/root' else os.getenv('SUDO_USER', os.getenv('USER'))
'ubuntu' # OK!

$ sudo su
$ python3
>>> import os
>>> 'root' if os.path.expanduser('~') == '/root' else os.getenv('SUDO_USER', os.getenv('USER'))
'root' #  OK!

$ sudo python3
>>> import os
>>> 'root' if os.path.expanduser('~') == '/root' else os.getenv('SUDO_USER', os.getenv('USER'))
'ubuntu' # OK!

Вопрос:

Как я могу получить имя текущего пользователя, использующего python script? Функция должна работать независимо от того, является ли она доменом/пользователем объявления или локальным пользователем.

Ответ №1

Попробуйте следующее:

import os;
print os.environ.get( "USERNAME" )

Это должно выполнить эту работу.

Ответ №2

как в qaru.site/questions/15985/… Константин Тензин

Посмотрите getpass module

import getpass
getpass.getuser()

Доступность: Unix, Windows

Примечание. “Эта функция смотрит на значения различной среды переменные для определения имени пользователя. Следовательно, эта функция должна не следует полагаться на цели контроля доступа (или, возможно, любые другие потому что он позволяет любому пользователю выдавать себя за другого).

по крайней мере, определенно предпочтительнее getenv.

Ответ №3

Ответ №4

Я не знаю Python, но для окон базовый api GetUserNameEx, я предполагаю, что вы можете называть это в Python, если os. environ.get( “USERNAME” ) не сообщает вам все, что вам нужно знать.

Ответ №5

Довольно старый вопрос, но для обновления ответа на исходный вопрос “Как получить имя текущего пользователя, использующего python script?”? Применение:

import os
print (os.getlogin())

Документация Per Python: getlogin – возвращает имя пользователя, зарегистрированного на управляющем терминале процесса.

Print Current User Account Name in Python

Here is the simple way to get the user name by using python code.

Note: It is adviced not to use this function for any authorization purpose as this can be manipulated. Because the getpass reads the data from environment variables (LOGNAME or USERNAME) and returns the username. Read the 2 external references mentioned at end of this page to know indepth details about this function.

Option 1: This code gets current logged in Username in Unix & Windows systems.

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

Option 2: There is another variant of the above function. Though this will also work in Unix & Windows, it is adviced to use the getpass, because it is more stable than other functions.

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

This command directly gets the user name and returns the name as string. getpass.getuser.

External References:

  1. Discussion on getting username using Python – Read more
  2. Further reading about getpass module – Read more

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.

import psutil

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:

  • How to Find and List All Running Processes in Python
  • Python Program to get IP Address of your Computer

Как я могу получить имя текущего пользователя, вошедшего в систему, с помощью скрипта Python? Функция должна работать независимо от того, является ли он пользователем домена / объявления или локальным пользователем.

5 ответы

Попробуй это:

import os;
print os.environ.get( "USERNAME" )

Это должно сработать.

как в https://stackoverflow.com/a/842096/611007 by Константин Тензин

смотреть на GetPass модуль

import getpass
getpass.getuser()

Доступность: Unix, Windows

Запись «эта функция смотрит на значения различных переменных среды, чтобы определить имя пользователя. Следовательно, на эту функцию не следует полагаться для целей управления доступом (или, возможно, для любых других целей, поскольку она позволяет любому пользователю выдавать себя за любого другого).«

по крайней мере, определенно предпочтительнее getenv.

ответ дан 23 мая ’17, 11:05

Я не знаю Python, но для окон базовый api GetUserNameEx, Я предполагаю, что вы можете вызвать это в Python, если os.environ.get («USERNAME») не сообщает вам все, что вам нужно знать.

Создан 22 сен.

Довольно старый вопрос, но чтобы обновить ответ на исходный вопрос «Как я могу получить имя текущего пользователя, вошедшего в систему, используя скрипт python?» использовать:

import os
print (os.getlogin())

Документация по Python: getlogin — возвращает имя пользователя, вошедшего в систему на управляющем терминале процесса.

ответ дан 30 мая ’14, 22:05

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

python
active-directory

or задайте свой вопрос.

Материал из Xgu.ru

Перейти к: навигация, поиск

Содержание

  • 1 Вопросы и ответы
    • 1.1 Как правильно узнать имя текущего пользователя?
    • 1.2 Как уникально идентифицировать анонимного пользователя?
      • 1.2.1 Как определить, сколько свободного места на диске?
    • 1.3 Есть какой-то хороший curses-тулкит для Python?
  • 2 Дополнительная информация
  • 3 Примечания

[править] Вопросы и ответы

[править] Как правильно узнать имя текущего пользователя?

def get_username():
    return pwd.getpwuid( os.getuid() )[ 0 ]

Или:

def get_username():
    return pwd.getpwuid( os.geteuid() )[ 0 ]

Другие способы: [1].

[править] Как уникально идентифицировать анонимного пользователя?

Идеи и предложения на ХэшКоде.

[править] Как определить, сколько свободного места на диске?

import os
import platform
import ctypes

def get_free_space(folder):
    """ Return folder/drive free space (in bytes)
    """
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
        return free_bytes.value
    else:
        return os.statvfs('/folder').f_bavail*os.statvfs('/folder').f_bsize #к-во доступных пользователю блоков*размер блока

Источник: [2]

[править] Есть какой-то хороший curses-тулкит для Python?

Например, Urwid

[править] Дополнительная информация

[править] Примечания

 Просмотр этого шаблона Информация о Python на xgu.ru
Реализации Cython  • Psyco  • PyPy Python logo.svg
Веб-фреймворки Django  • Flask  • Zope
IDE Pydev  • NetBeans
Курсы Python для сетевых инженеров
Другое aalib  • ctypes  • gevent  • mpmath  • pjsua  • Pandas  • pyparsing  • virtualenv  • GMPY  • IPython  • Jinja2  • Python и Vim  • Работа с модулями в Python  • SWIG  • Scapy  • SciPy  • Работа с датой и временем в Python  • Python как shell  • Web и Python  • Алгоритмы, сложные структуры данных и дискретная математика в Python  • Анализ кода Python  • Интеграция Python с другими языками  • Объекты и классы в Python  • Оформление кода Python  • Параллелизм и конкурентное исполнение в Python  • Профайлинг в Python  • Работа с базами данных в Python  • Работа с операционной системой в Python  • Работа с сетью в Python  • Работа с текстами в Python  • Работа с файлами в Python  • Сравнение Python с другими языками  • Тестирование в Python  • Типы в Python  • Элементы функционального программирования в Python  • Элементы языка Python

Понравилась статья? Поделить с друзьями:
  • Как получить иконку приложения в windows 10
  • Как получить изображение со сканера windows 10
  • Как получить изображение с веб камеры windows 7
  • Как получить доступ от системы на удаление папки windows 10
  • Как получить доступ ко всем файлам windows 10