前回作成したパスワード生成スクリプト。変数で指定するのはCron処理などでは便利でしたが、日常には不向き。
そこで、再びChatGPTに相談し、
以下の要件でスクリプトを作成です。
要件
- スクリプトを実行する
 - 発行強度を1~3で指定する (空エンターは中)
- 1:弱 8桁/英数字のみ
 - 2:中 10桁/小文字・大文字・英数字と単純な記号
 - 3.強 12桁/小文字・大文字・英数字と複雑な記号
 
 - 表示するパスワードの数を数字で指定する (空エンターは4個)
 
スクリプト
できあがったのがこちら。
- password_generate.rb
 
def generate_password(length, complexity, password_count)
  case complexity
  when 1
    chars = [('a'..'z'), (0..9)].map(&:to_a).flatten
  when 2
    chars = [('a'..'z'), ('A'..'Z'), (0..9), ['!', '@', '#', '$', '%', '^', '&', '*']].map(&:to_a).flatten
  when 3
    chars = [('a'..'z'), ('A'..'Z'), (0..9), ['!', '@', '#', '$', '%', '^', '&', '*'], ['-', '_', '=', '+', '<', '>', '?']].map(&:to_a).flatten
  else
    puts "無効な発行強度です。"
    return
  end
  password_count.times do |i|
    password = (0...length).map { chars[rand(chars.length)] }.join
    puts "Password #{i + 1}: #{password}"
  end
end
def get_complexity
  print "発行強度を1から3の範囲で入力してください (デフォルトは2):\n"
  complexity_input = gets.chomp
  complexity = complexity_input.empty? ? 2 : complexity_input.to_i
  until (1..3).cover?(complexity)
    print "有効な範囲で入力してください(1から3): "
    complexity = gets.chomp.to_i
  end
  complexity
end
def get_password_count
  print "表示するパスワードの数を入力してください (デフォルトは4): "
  count_input = gets.chomp
  count = count_input.empty? ? 4 : count_input.to_i
  count
end
puts "パスワードを生成します。"
complexity = get_complexity
password_count = get_password_count
case complexity
when 1
  generate_password(8, complexity, password_count)
when 2
  generate_password(10, complexity, password_count)
when 3
  generate_password(12, complexity, password_count)
end
実行例
ruby password_generate.rb
発行強度を1から3の範囲で入力してください (デフォルトは2):
2
表示するパスワードの数を入力してください (デフォルトは4): 9
Password 1: ILAXRn!O47
Password 2: P^qmiduucK
Password 3: 8ytFezU%fU
Password 4: O!6OFeHgYe
Password 5: Ua&!Ryg039
Password 6: &T@AtiNpWy
Password 7: Jz8jyPbp#3
Password 8: HOWE66ki1I
Password 9: 9WRdsHhk*H
								
			
コメントを残す