How to print all linux users with Puppet and ruby? - ruby

I want to create a facter that returns all users.
Facter.add("sysusers") do
setcode do
File.readlines('/etc/passwd').each do |line|
line.match(/^[^:]+/)[0]
end
end
end
Then in my .pp file I have this:
$users = inline_template("<%= scope.lookupvar('sysusers') %>")
$users.each |String $user| {
notify { "$user":}
}
This should work but the facter returns just one letter at a time.
So notify { "$user":} just prints:
Notify[r]
Notify[o]
And then it craches because the next letter is also "o" (two o`s in "root" and root is the first user stated in /etc/passwd).
So how can I print all the users?
EDIT
With the edit to:
Facter.add("sysusers") do
setcode do
File.readlines('/etc/passwd').each do |line|
line.match(/^[^:]+/).to_s
end
end
end
Then the output is:
root#mymachine]# facter sysusers
[
"root:x:0:0:root:/root:/bin/bash
",
"bin:x:1:1:bin:/bin:/usr/bin/nologin
",
"daemon:x:2:2:daemon:/:/usr/bin/nologin
...
...
So it still does not seem to work as expeced.

This is the match you want.
line.match(/^[^:]+/).to_s
When you add [0], it is taking the first character from the string that is the user name.
EDIT
File.readlines('/etc/passwd').collect do |line|
line.match(/^[^:]+/).to_s
end
That will collect an array which to be returned in your setcode.

Parsing /etc/passwd is a clunky approach to your problem.
It's cleaner to use the Etc module
require 'etc'
result = []
Etc.passwd { |user| result << user.name }
result

Use the following ruby code, which reads and prints the user names from /etc/passwd file.
IO.readlines("/etc/passwd").each do |val|
user = val.split(":").first
puts user
end

Related

How to valid input to matches data in CSV file

I'm using Ruby 2.7 above. I've been working this task and still learning. I'm pretty sure that I am not using the right code. This task require me to do a mimic atm program. One of the requirements is where I need to check user valid inputs are matches the data in the CSV.file before user can access the program.
I'm using ruby (not allowed to use rails or any advance ruby code). I searched for similar program anywhere for reference but mostly does not involve with CSV file. How do I check that input from user is valid and matches in CSV file? I'm having trouble on how to do a validation and how to valid with two inputs (username and password). This program is run on command-line. Apologies if im not being clear enough. Can you tell me from my code where I'm going wrong please?
I have three .rb files and two csv files. I am not sure if I'm supposed to create two separate csv files.
function.rb (where all the functions)
login.rb (verify username and password from 'user.csv' file before proceed to system.rb file)
system.rb (the main where all data save or changes in 'account.csv' file)
below is function.rb file.
require 'csv'
class Function
def log_in(user)
CSV.foreach('user.csv', 'r', headers => true) do |row|
#check the user is valid, else error
if row[0] == uname && row[1] == pwd
puts "succesfully login"
ATMSystem.main_menu
end
end
if login == false
puts "invalid credentials."
Login.log_menu
end
end
login.rb file
require './function'
class Inn
def signin
function = AtmFunction.new
puts "Account login"
puts "Enter username"
uname = gets.chomp
puts "Enter password"
pwd = gets.chomp
user = [uname, pwd]
function.log_in(user)
end
end
Let's say this is your users.csv file:
name,password
bob,1234
alice,5678
This is one possible option.
Load the file into an array of hashes Enumerable#to_h and Hash#transform_keys:
require 'csv'
data_file = 'user.csv'
user_map = CSV.foreach(data_file, headers: true).map do |row|
row.to_h.transform_keys(&:to_sym)
end
user_map
#=> [{:name=>"bob", :password=>"1234"}, {:name=>"alice", :password=>"5678"}]
Then, given the input from the user:
input_username = 'bob'
input_password = '1234'
Check if user exists and in case compare the password:
user = user_map.find { |h| h[:name] == input_username }
#=> {:name=>"bob", :password=>"1234"}
user[:password] == input_password
#=> true
Check the password if Enumerable#find returns a non nil value: the user doesn't exist:
input_username = 'ron'
user = user_map.find { |h| h[:name] == input_username }
user
#=> nil
Following your implementation you can also write:
login_passed = false
CSV.foreach(data_file, headers: true) do |row|
login_passed = row['name'] == input_username && row['password'] == input_password
break if login_passed
end
login_passed
#=> true (or false)

Ruby retrieve data from file after specific label

How can I get specific data from a file in ruby? I want to get some 10. ip addresses from a file set up like this...
Whatever: xathun
ip_address: 10.2.232.6
etc: aouoeu
more: snthuh
I want to push the ip addresses into an array.
I can pull 10. addresses out of text. I was hoping for a more accurate way to do it as in only the data after the 'ip_address:' label in case there is unwanted matching data.
s_text = File.open("test.txt",'r').read
ip_addresses = s_text.scan(/\d+.\d+.\d+.\d+/)
puts ip_addresses.inspect #=> ["10.2.232.6"]
Here's a simple enough solution.
open('<textfile path>') { |f| puts f.grep(/10\./) }
If the file is setup like that throughout you can do:
arr = []
File.open("text").each_line do |line|
parts = line.split(":")
arr << parts[1].strip if parts[0] == "ip_address"
end
adding to array as you go through once, one line at a time:
ip_data.txt
Whatever: xathun
ip_address: 10.2.232.6
etc: aouoeu
more: snthuh
Whatever: badone
ip_address: 66.8.103.3
etc: huh
more: noooo
Whatever: blah
ip_address: 10.9.244.13
etc: hello
more: goodbye
code
found_tens = []
File.open('ip_data.txt') {|f|
f.each {|line|
line = line.chomp
next if line.empty?
found_tens << $1 if line =~ /^ip_address:\s+(10\.\d+\.\d+\.\d+)/
}
}
p found_tens #["10.2.232.6", "10.9.244.13"]

trying to find the 1st instance of a string in a CSV using fastercsv

I'm trying to open a CSV file, look up a string, and then return the 2nd column of the csv file, but only the the first instance of it. I've gotten as far as the following, but unfortunately, it returns every instance. I'm a bit flummoxed.
Can the gods of Ruby help? Thanks much in advance.
M
for the purpose of this example, let's say names.csv is a file with the following:
foo, happy
foo, sad
bar, tired
foo, hungry
foo, bad
#!/usr/local/bin/ruby -w
require 'rubygems'
require 'fastercsv'
require 'pp'
FasterCSV.open('newfile.csv', 'w') do |output|
FasterCSV.foreach('names.csv') do |lookup|
index_PL = lookup.index('foo')
if index_PL
output << lookup[2]
end
end
end
ok, so, if I want to return all instances of foo, but in a csv, then how does that work?
so what I'd like as an outcome is happy, sad, hungry, bad. I thought it would be:
FasterCSV.open('newfile.csv', 'w') do |output|
FasterCSV.foreach('names.csv') do |lookup|
index_PL = lookup.index('foo')
if index_PL
build_str << "," << lookup[2]
end
output << build_str
end
end
but it does not seem to work
Replace foreach with open (to get an Enumerable) and find:
FasterCSV.open('newfile.csv', 'w') do |output|
output << FasterCSV.open('names.csv').find { |r| r.index('foo') }[2]
end
The index call will return nil if it doesn't find anything; that means that the find will give you the first row that has 'foo' and you can pull out the column at index 2 from the result.
If you're not certain that names.csv will have what you're looking for then a bit of error checking would be advisable:
FasterCSV.open('newfile.csv', 'w') do |output|
foos_row = FasterCSV.open('names.csv').find { |r| r.index('foo') }
if(foos_row)
output << foos_row[2]
else
# complain or something
end
end
Or, if you want to silently ignore the lack of 'foo' and use an empty string instead, you could do something like this:
FasterCSV.open('newfile.csv', 'w') do |output|
output << (FasterCSV.open('names.csv').find { |r| r.index('foo') } || ['','',''])[2]
end
I'd probably go with the "complain if it isn't found" version though.

How do I get all the files names in one folder using Ruby?

These are in a folder:
This_is_a_very_good_movie-y08iPnx_ktA.mp4
myMovie2-lKESbDzUwUg.mp4
his_is_another_movie-lKESbDzUwUg.mp4
How do I fetch the first part of the string mymovie1 from the file by giving the last part, y08iPnx_ktA? Something like:
get_first_part("y08iPnx_kTA") #=> "This_is_a_very_good_movie"
Break the problem into into parts. The method get_first_part should go something like:
Use Dir to get a listing of files.
Iterate over each file and;
Extract the "name" ('This_is_a_very_good_movie') and the "tag" ('y08iPnx_ktA'). The same regex should be used for each file.
If the "tag" matches what is being looked for, return "name".
Happy coding.
Play around in the REPL and have fun :-)
def get_first_part(path, suffix)
Dir.entries(path).find do |fname|
File.basename(fname, File.extname(fname)).end_with?(suffix)
end.split(suffix).first
end
Kind of expands on the answer from #Steve Wilhelm -- except doesn't use glob (there's no need for it when we're only working with filenames), avoids Regexp and uses File.exname(fname) to the File.basename call so you don't have to include the file extension. Also returns the string "This_is_a_very_good_movie" instead of an array of files.
This will of course raise if no file could be found.. in which case if you just want to return nil if a match couldn't be found:
def get_first_part(path, suffix)
file = Dir.entries(path).find do |fname|
File.basename(fname, File.extname(fname)).end_with?(suffix)
end
file.split(suffix).first if file
end
Can it be done cleaner than this? REVISED based on #Tin Man's suggestion
def get_first_part(path, suffix)
Dir.glob(path + "*" + suffix + "*").map { |x| File.basename(x).gsub(Regexp.new("#{suffix}\.*$"),'') }
end
puts get_first_part("/path/to/files/", "-y08iPnx_kTA")
If the filenames only have a single hyphen:
path = '/Users/greg/Desktop/test'
target = 'rb'
def get_files(path, target)
Dir.chdir(path) do
return Dir["*#{ target }*"].map{ |f| f.split('-').first }
end
end
puts get_files(path, 'y08iPnx_ktA')
# >> This_is_a_very_good_movie
If there are multiple hyphens:
def get_files(path, target)
Dir.chdir(path) do
return Dir["*#{ target }*"].map{ |f| f.split(target).first.chop }
end
end
puts get_files(path, 'y08iPnx_ktA')
# >> This_is_a_very_good_movie
If the code is assumed to be running from inside the directory containing the files, then Dir.chdir can be removed, simplifying things to either:
puts Dir["*#{ target }*"].map{ |f| f.split('-').first }
# >> This_is_a_very_good_movie
or
puts Dir["*#{ target }*"].map{ |f| f.split(target).first.chop }
# >> This_is_a_very_good_movie

Ruby regular expressions - speed problem

I want to obtain the information of students in class c79363 ONLY.
The following file(users.txt) contains the user id's
c79363::7117:dputnam,gliao01,hmccon01,crober06,cpurce01,cdavid03,dlevin01,jsmith88
d79363::7117:dputn,gliao0,hmcc01,crob06,cpur01,cdad03,dlen01,jsmh88
f79363::7117:dpnam,gli01,hmcn01,ober06,crce01,cdav03,dln01,jith88
FILENAME=user_info.txt
The other one contains specific information about a user like in this format
jsmith88:*:4185:208:jsmith113:/students/jsmith88:/usr/bin/bash
userd:*:4185:208:jsmith113:/students/jsmith88:/usr/bin/bash
gliao01:*:4185:208:jsmith113:/students/jsmith88:/usr/bin/bash
Here was my solution but was slow! I want to optimize the speed.
pseudo code
I read the file using File.readlines(users.txt) ->
I used split(/,/) -> I then pop array until i had an array with the following values
dputnam,gliao01,hmccon01,crober06,cpurce01,cdavid03,dlevin01,jsmith88
I then continue to read user_info.txt with File.readlines(user_info.txt)
I split(/:/) i have USER ARRAY
Finally I compared the first entry USER ARRAY with my users in class c79363.
user_info = {}
File.foreach("user_info.txt") {|line| user_info[line[/^[^:]+/]] = line.chomp}
class_name = "c79363"
File.foreach("users.txt") do |line|
next unless line[/^[^:]+/] == class_name
line[/[^:]+$/].rstrip.split(/,/).each do |user|
puts user_info[user] if user_info.has_key?(user)
end
end
user_info = {}
File.readlines("users_info.txt").each do |line|
user_info[line.split(/:/,2)[0]] = line.chomp
end
class_name = "c79363"
File.readlines("users.txt").each do |line|
line=line.strip.split(/:/)
if line[0] == class_name then
line[-1].split(",").each {|u| puts user_info[u] if user_info[u] }
end
end

Resources