2010-03-29 14 views

risposta

17

Questa risposta si basa sul numero answer by Brian. Aggiunge il blocco try...except necessario.

controllare se un utente esiste:

import pwd 

try: 
    pwd.getpwnam('someusr') 
except KeyError: 
    print('User someusr does not exist.') 

Verificare se un gruppo esiste:

import grp 

try: 
    grp.getgrnam('somegrp') 
except KeyError: 
    print('Group somegrp does not exist.') 
9

per cercare il mio userid (bagnew) sotto Unix:

import pwd 
pw = pwd.getpwnam("bagnew") 
uid = pw.pw_uid 

Vedi informazioni modulo pwd di più.

+1

alzerà 'KeyError 'se il nome utente non è stato trovato. –

+1

Abbiamo trovato ulteriori informazioni qui: http://www.doughellmann.com/PyMOTW/pwd/ – Elifarley

+0

Ora ho aggiunto una risposta con il necessario "prova ... tranne". –

0

Analizzerei/etc/passwd per il nome utente in questione. Gli utenti potrebbero non avere necessariamente homedir's.

+2

Questo fallirà se ad es. LDAP è in uso. –

+0

+1 per aver menzionato che gli utenti potrebbero non avere necessariamente degli homedir. –

+0

Ho avuto l'impressione che non tutti i sapori di linux memorizzino le informazioni utente nel file/etc/passwd ... – Powertieke

2

Utilizzando pwd è possibile ottenere un elenco di tutte le voci utente disponibili utilizzando pwd.getpwall(). Questo può funzionare se non ti piace provare:/except: blocks.

import pwd 

userid = "zomobiba" 
if userid in [x[0] for x in pwd.getpwall()]: 
    print "Yay" 
+2

Ok, ma non vi è alcun motivo per non apprezzare i blocchi "prova ... tranne". È anche più efficiente interrogare un singolo utente con 'getpwnam' piuttosto che interrogare tutti gli utenti con' getpwall'. –

0

Simile a this answer, farei questo:

>>> import pwd 
>>> 'tshepang' in [entry.pw_name for entry in pwd.getpwall()] 
True 
Problemi correlati