Python: Get Windows username of user viewing page?
Is there a way in Python/Django to get the username of the currently logged-in Windows user, from an app that is not running locally?
UPDATE: sorry, to clarify, by this I mean the Windows username of the user viewing the web page, not the user running the server.
But I think they’re returning the name of the user running the server.
FURTHER UPDATE: I don’t care greatly about security. It really doesn’t matter if users spoof a username. What does matter is convenience. I just need a way to get the username without users having to fiddle around with passwords or install client-side software. Any ideas?
1 Answer 1
Three ways, none of which work.
Use the Ident (AUTH) protocol. It’s technically cross-platform.
. except there are exactly zero Ident servers for Windows that are able to return the real user name instead of a static string.
Require HTTP NTLM or Negotiate authentication. You get more than a mere username check,
. except NTLM is insecure, only Internet Exploder and Firefox support it, and they only use it inside the LAN (intranet) by default. Negotiate is able to use the more secure Kerberos, but it (obviously) requires Kerberos on both server and clients. If the Windows PCs are in a domain, good. If not.
If you control all client machines, you can use simple SSL client-certificate authentication. Works in all modern browsers.
. but every user needs their own certificate. Creating an internal-use CA and issuing certificates is simple; getting them installed and working in client machines — not so.
Is there a portable way to get the current username in Python?
Is there a portable way to get the current user’s username in Python (i.e., one that works under both Linux and Windows, at least). It would work like os.getuid :
I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The pwd module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven’t verified that.
13 Answers 13
Look at getpass module
Availability: Unix, Windows
p.s. Per comment below «this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other).«
You best bet would be to combine os.getuid() with pwd.getpwuid() :
Refer to the pwd docs for more details:
You can also use:
You can probably use:
But it’s not going to be safe because environment variables can be changed.
These might work. I don’t know how they behave when running as a service. They aren’t portable, but that’s what os.name and if statements are for.
If you are needing this to get user’s home dir, below could be considered as portable (win32 and linux at least), part of a standard library.
Also you could parse such string to get only last path component (ie. user name).
To me using os module looks the best for portability: Works best on both Linux and Windows.
No need of installing any modules or extensions.
Combined pwd and getpass approach, based on other answers:
For UNIX, at least, this works.
edit: I just looked it up and this works on Windows and UNIX:
On UNIX it returns your username, but on Windows, it returns your user’s group, slash, your username.
UNIX returns: «username»
Windows returns: «domain/username»
It’s interesting, but probably not ideal unless you are doing something in the terminal anyway. in which case you would probably be using os.system to begin with. For example, a while ago I needed to add my user to a group, so I did (this is in Linux, mind you)
I feel like that is easier to read and you don’t have to import pwd or getpass.
I also feel like having «domain/user» could be helpful in certain applications in Windows.
Username
В функцию big_data() передается произвольное количество кортежей, в которых записана информация о пользователях системы (id, дата изменения в формате DD-MM-YYYY, email) и именованная переменная key с ключом сортировки. По умолчанию сортировка по возрастанию id.
Нужно в каждый кортеж в конец добавить логин, который получается из электронного адреса, если взять только то, что записано до @ и перевести первую букву в верхний регистр (остальные в нижний), а также дописать в конец логина три цифры: первая от дня, последняя от месяца и последняя от года. Функция возвращает список измененных кортежей, отсортированных по ключу.
Пример
Ввод
data = [(123, ’14-05-2020′, ‘username@gmail.com’),
(21, ’12-06-2020′, ‘ara@gmail.com’),
(4123, ’02-09-2020′, ‘unknown@yandex.ru’),
(1253, ’17-05-2020′, ‘qwerty@mail.ru’)]
func = lambda x: x[-1]
Вывод
print(*big_data(*data, key=func), sep=’\n’)
(21, ’12-06-2020′, ‘ara@gmail.com’, ‘Ara160’)
(1253, ’17-05-2020′, ‘qwerty@mail.ru’, ‘Qwerty150’)
(4123, ’02-09-2020′, ‘unknown@yandex.ru’, ‘Unknown090’)
(123, ’14-05-2020′, ‘username@gmail.com’, ‘Username150’)
UNIQUE constraint failed: account_user.username
Здравствуйте, с медиа файлами я только начал работать, так что извиняюсь за глупый вопрос. Если.
Requests — Русские символы в Username веб-сервиса
Добрый день! Прошу не судить строго, но столкнулся со следующей проблемой: есть веб-сервис, к.
Telegram api Как получить @username последнего добавленного контакта или @username по номеру телефона
Teegram api Как получить @username последнего добавленного контакта или @username по номеру телефона
UserName
Здравствуйте. Учусь делать сайт по Эспозито и возникла проблема с редактором профиля.
how to get username and domain of windows logged in client using python code?
when user logs in to his desktop windows os authenticates him against Active Directory Server. so Whenever he accesses a web page he should not be thrown a login page for entering his userid or password.Instead, his userid and domain need to be captured from his desktop and passed to the web server.(let him enter password after that)
Is this possible in python to get username and domain of of client? win32api.GetUserName() gives the username of the server side.
Thanks in advance
3 Answers 3
Hmm. what you probably want to do is use Django’s RemoteUserMiddleware and leave user authentication to the Web Server which can then be configured to handle it. The solution from Ntlm/Kerberos authentication in Django should work, but as mentioned it’s a bit quirky — not all browsers support it correctly, and you have to modify browser settings for it to work.
What you want to do is called Single sign on (SSO) and it’s much easier to implement on actual web server than Django.
So, you should check how to do SSO on Apache/Nginx/whateverYouAreUsing, then the web server will forward the authenticated username to your django app.
This sounds like a javascript question to me. I think you’ll have to add javascript to your login page that attempts to access the details and returns them to the server.
I would have thought that there would be security measures to prevent this, however this question suggests others have managed something similar.
It looks like there might be some useful information in the django docs