该脚本的目标是为useradd linux命令生成用户名。我还希望将具有相同名称的名称以相同顺序放入具有新生成的名称和密码的新CSV文件中。
到目前为止,我已经具有通过读取CSV文件来生成新名称的脚本。
CSV文件的前两行如下所示。
first_name, last_name
Briana, Considine
这是脚本工作的一部分:
filename = 'employeedata.csv'
CSV.foreach(filename, headers: true) do |row|
first_name_char = row['first_name'].strip.split('')
useradd_name = "#{row['last_name']}#{first_name_char.first}#{first_name_char.last}"
password = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}
system("useradd '#{useradd_name}'")
puts useradd_name
puts password
这是脚本中出错的部分。
CSV.open("GeneratedUsers.csv", "w") do |outfile|
outfile << ["First Name", "Last Name:", "Username:"] #to make the new headers
outfile << "#{row['first_name']}" #import firstname from employeedata.csv
end
end
这是我得到的错误:
Traceback (most recent call last):
17: from Nick_Hyder_Project3.rb:19:in `<main>'
16: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:509:in `foreach'
15: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:657:in `open'
14: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:510:in `block in foreach'
13: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:1236:in `each'
12: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:1236:in `each'
11: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:303:in `parse'
10: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:779:in `parse_quotable_loose'
9: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:28:in `each_line'
8: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:28:in `each_line'
7: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:31:in `block in each_line'
6: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:827:in `block in parse_quotable_loose'
5: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:1078:in `emit_row'
4: from Nick_Hyder_Project3.rb:25:in `block in <main>'
3: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:657:in `open'
2: from Nick_Hyder_Project3.rb:27:in `block (2 levels) in <main>'
1: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:1186:in `<<'
C:/Ruby26-x64/lib/ruby/2.6.0/csv/writer.rb:37:in `<<': undefined method `collect' for "Briana":String (NoMethodError)
在将新的用户名和密码添加到新列之前,有没有办法复制所有旧文件?还是我需要逐行编写新的CSV?
outfile << "#{row['first_name']}"
应该是:
outfile << [row['first_name']]