So now we will start putting Ruby to work so we see some benefits to our learning efforts. In this tutorial we will look at how we can use Ruby to create users on our Linux host and have their passwords set using the crypt function.
Creating users for my classes can be a little tiresome sometimes, generally I use simple passwords and I need to create multiple accounts with the same password. Linux will complain, even as root that the passwords are simple, but using useradd and the -p switch we can bypass the complaining passwd program. But useradd expects and encrypted password so we need to access the crypt api.
This we do with the line
pwd = pw.crypt("$5$a1")
The crypt method we access takes the SALT as an argument. the first part of this $5 specifies that we will use SHA-256 encryption, use $6 if you wold like SHA-512. $a1 then becomes the random SALT we apply to crypt. So we can easily add our Linux users with passwords correctly set.
To add the users with passwords we use the line:
result = system("useradd -m -p '#{ pwd }' #{ uname }")
Note the single quotes around the pwd variable, as we do not want the dollars to be expanded. If we left this out the password would be mis-set as the $would be read as variables. Using the single quotes then they are interpreted as literals.
I have included the complete script for your use below:
#!/usr/bin/ruby require 'io/console' def do_create_user(no,us,pw) pwd = pw.crypt("$5$a1") 1.upto(no) do | x | uname = us + x.to_s result = system("useradd -m -p '#{ pwd }' #{ uname }") if result puts "#{ uname } created!" else puts "#{ uname } failed!" end end end print "How many users do you want? " count = gets.chomp.to_i print "Enter the username suffix, user, u etc... " user = gets.chomp.downcase print "Enter Password: " password = STDIN.noecho(&:gets).chomp puts "" # print an empty line do_create_user(count,user,password)
Now the video: