Pastey How to read passwd and group files on Linux
- Posted by ghaberek
(admin)
Feb 25, 2019
include std/io.e
include std/sequence.e
include std/convert.e
public enum
U_NAME,
U_PASS,
U_UID,
U_GID,
U_DESC,
U_HOME,
U_SHELL
public enum
G_NAME,
G_PASS,
G_GID,
G_LIST
function read_passwd( sequence file )
object passwd = read_lines( file )
if atom( passwd ) then
return {}
end if
for i = 1 to length( passwd ) do
passwd[i] = split( passwd[i], ':' )
-- parse these values to integers
passwd[i][U_UID] = to_integer( passwd[i][U_UID] )
passwd[i][U_GID] = to_integer( passwd[i][U_GID] )
end for
return passwd
end function
function read_groups( sequence file )
object groups = read_lines( file )
if atom( groups ) then
return {}
end if
for i = 1 to length( groups ) do
groups[i] = split( groups[i], ':' )
-- parse this value to an integer
groups[i][G_GID] = to_integer( groups[i][G_GID] )
-- parse this value to a sequence
groups[i][G_LIST] = split( groups[i][G_LIST], ',' )
end for
return groups
end function
public function find_user( sequence name, sequence file = "/etc/passwd" )
sequence passwd = read_passwd( file )
for i = 1 to length( passwd ) do
if equal( passwd[i][U_NAME], name ) then
return passwd[i]
end if
end for
return 0
end function
public function find_uid( integer uid, sequence file = "/etc/passwd" )
sequence passwd = read_passwd( file )
for i = 1 to length( passwd ) do
if equal( passwd[i][U_UID], uid ) then
return passwd[i]
end if
end for
return 0
end function
public function find_group( sequence name, sequence file = "/etc/group" )
sequence groups = read_groups( file )
for i = 1 to length( groups ) do
if equal( groups[i][G_NAME], name ) then
return groups[i]
end if
end for
return 0
end function
public function find_gid( integer gid, sequence file = "/etc/group" )
sequence groups = read_groups( file )
for i = 1 to length( groups ) do
if equal( groups[i][G_GID], gid ) then
return groups[i]
end if
end for
return 0
end function
-- examples
include std/pretty.e
pretty_print( 1, find_user("greg"), {2} ) puts( 1, "\n" )
pretty_print( 1, find_uid(33), {2} ) puts( 1, "\n" )
pretty_print( 1, find_group("sudo"), {2} ) puts( 1, "\n" )
pretty_print( 1, find_gid(4), {2} ) puts( 1, "\n" )
-- output
-- {
-- "greg",
-- "x",
-- 1000,
-- 1000,
-- "Greg Haberek,,,",
-- "/home/greg",
-- "/bin/bash"
-- }
-- {
-- "www-data",
-- "x",
-- 33,
-- 33,
-- "www-data",
-- "/var/www",
-- "/usr/sbin/nologin"
-- }
-- {
-- "sudo",
-- "x",
-- 27,
-- {
-- "greg"
-- }
-- }
-- {
-- "adm",
-- "x",
-- 4,
-- {
-- "syslog",
-- "greg"
-- }
-- }