Module: Capricorn::System::ProcessUser

Included in:
Capricorn::System
Defined in:
lib/capricorn/system/process_user.rb

Instance Method Summary collapse

Instance Method Details

#as_user(username, groupname = nil, &block) ⇒ Object

run the passed block as the specified user and group



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/capricorn/system/process_user.rb', line 57

def as_user(username, groupname=nil, &block)
  euid = Process.euid
  egid = Process.egid
  
  value = nil
  begin
    switch_to_user(username, groupname)
    value = block.call
  ensure
    switch_to_user(euid, egid)
  end
  value
end

#get_gid(groupname) ⇒ Object

get the gid for a group name



13
14
15
16
# File 'lib/capricorn/system/process_user.rb', line 13

def get_gid(groupname)
  return groupname if Numeric === groupname
  Etc.getgrnam(groupname).gid
end

#get_group_name(gid = Process.gid) ⇒ Object

get the group name for a gid (or the current process group)



25
26
27
28
# File 'lib/capricorn/system/process_user.rb', line 25

def get_group_name(gid=Process.gid)
  return gid if String === gid
  Etc.getgrgid(gid).name
end

#get_uid(username) ⇒ Object

get the uid for a user name



7
8
9
10
# File 'lib/capricorn/system/process_user.rb', line 7

def get_uid(username)
  return username if Numeric === username
  Etc.getpwnam(username).uid
end

#get_user_name(uid = Process.uid) ⇒ Object

get the user name for a uid (or the current process user)



19
20
21
22
# File 'lib/capricorn/system/process_user.rb', line 19

def get_user_name(uid=Process.uid)
  return uid if String === uid
  Etc.getpwuid(uid).name
end

#is_group(groupname) ⇒ Object

is this process running as this group?



37
38
39
40
# File 'lib/capricorn/system/process_user.rb', line 37

def is_group(groupname)
  gid = get_gid(groupname)
  Process.egid == gid and Process.gid == gid
end

#is_user(username) ⇒ Object

is this process running as this user?



31
32
33
34
# File 'lib/capricorn/system/process_user.rb', line 31

def is_user(username)
  uid = get_uid(username)
  Process.euid == uid and Process.uid == uid
end

#switch_to_user(username, groupname = nil) ⇒ Object

switch this user to the specified user and group



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/capricorn/system/process_user.rb', line 43

def switch_to_user(username, groupname=nil)
  different_uid = (Process.euid != get_uid(username))
  different_gid = (Process.egid != get_gid(groupname)) if groupname
  
  if groupname and different_gid
    Process.gid = Process.egid = get_gid(groupname)
  end
  
  if different_uid
    Process.uid = Process.euid = get_uid(username)
  end
end