Method: Cfruby::Users::UserManager#set_password

Defined in:
lib/libcfruby/users.rb

#set_password(user, newpassword) ⇒ Object

Sets the password of user to newpassword



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/libcfruby/users.rb', line 263

def set_password(user, newpassword)
  # We are going to do this with an expect script instead of in pure ruby...
  # partly because doing it in pure ruby turns out to be pretty tricky since
  # ruby doesn't have very good tools for interacting with shell programs, but
  # also because Expect does, and we like doing things with the right tool
  
  Cfruby.controller.attempt("Changing password for \"#{user}\"", 'destructive') {
    # we must be running as root
    if(Process.euid() != 0)
      raise(ChangePasswordError, "Passwords can only be set by root")
    end
  
    # first check for the existence of expect
    haveexpect = `/usr/bin/env expect -v`
    if(haveexpect !~ /expect version/i)
      raise(ChangePasswordError, "Expect binary could not be found")
    end
  
    # create a specialized expect script to change the password
    # and run it
    changepass = "#!/usr/bin/env expect\n\nspawn passwd \#{Cfruby::Exec.shellescape(user)}\nset password \"\#{newpassword.gsub(/(\")/, \"\\\\\\1\")}\"\nexpect \"New password:\"\nsend \"$password\\\\r\"\nexpect \"password:\"\nsend \"$password\\\\r\"\nexpect eof\n"

    scriptfile = Tempfile.new('cfruby')
    Cfruby::FileOps.chmod(scriptfile.path, "u+x,go-rwx")
    scriptfile.print(changepass)
    scriptfile.close(false)
    `cp #{scriptfile.path} ./footest`
    output = Cfruby::Exec.exec(scriptfile.path)
  }
end