UNIXのユーザ作成
ユーザ作成と一時的使用のパスワードを発行するのが面倒なので、自動生成するスクリプトの作業履歴。
そのうちexpireとか機能追加しないと。
#!/usr/bin/ruby require 'etc' # salt def getRandomString (length = 15) source=("a".."z").to_a + ("A".."Z").to_a + (0..9).to_a + ["_","-","."] key="" length.times{ key+= source[rand(source.size)].to_s } return key end username = ARGV[0] login = Etc.getpwuid(Process.uid).name unless login == "root" puts "exec root only!." exit 2 end unless ARGV.size == 1 puts "usage: #{__FILE__} [uername]" exit 2 end a = Array.new h = Hash.new Etc.passwd { |pwd| a << pwd.uid.to_i h[pwd.name] = 1 } next_max = a.max + 1 if h.key?(username) puts "#{__FILE__}: user #{username} exists" exit 9 end passwd = getRandomString cryptpasswd = passwd.crypt(username) exec_command = "/usr/sbin/useradd -g dev -p #{cryptpasswd} -s /bin/bash -d /home/#{username} #{username}" begin system(exec_command) rescue puts "system() error!" puts " - #{exec_command}" exit 2 else puts "Success:" puts " - username: #{username}" puts " - password: #{passwd}" end
実行するとこんな感じ。
$ sudo ./user_create.rb foobar Success: - username: foobar - password: sQvVLtlIpGDiymY