On 02/04/2010 11:58 AM, John Y. wrote:
Address2
puts Login
First question : how can i see the line after ? the line with the Ip
address of that login
You could use #each_slice for this (see below).
Second question : I don’t search always the same pattern so i need to
pass an argument to my script. I tried this
Login= File.open(“users” ).each_line.grep( /ARGV[0]/ )
puts Login
but it doesn’t show anything
You need string interpolation in the regular expression. In your case
the regexp will match if there is “ARGV0” somewhere in the string -
certainly not what you wanted.
If your file only contains login and password alternating you could do
def lookup(file, user)
File.foreach(file).each_slice 2 do |name, pwd|
name.strip!
pwd.strip!
return pwd if user === name
end
not found
nil
end
So, how does this work? File.foreach(file) without a block creates an
Enumerator, i.e. something that behaves like an Enumerable. With
#each_slice(2) iteration will yield two subsequent values at a time:
irb(main):012:0> (1…10).each_slice 2 do |a| p a end
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
=> nil
irb(main):013:0>
Now we have File.foreach(file) instead of 1…10 so what happens here is
that lines are read from the file and returned in pairs to the block.
The block checks whether there is a match (after removing trailing
newlines) and returns from the method if it finds something.
You can use this with regular expressions and Strings because of ===:
pwd = lookup “users”, ARGV[0]
pwd = lookup “users”, /#{ARGV[0]}/
If you want to do string matching and need to match multiple times
during a single script execution you could as well load the file into a
Hash
user_password = Hash[*(File.foreach(file).map {|s| s.chomp})]
This will work only if your file has an even number of lines though.
Third question : After having the ip address, i need to make an ssh
connection to this address. How can i get a variable to be usable in
system(“ssh $variable”) ?
You can use regular string interpolation
system “ssh #{your_variable}”
AFAIK there is also a SSL / SSH library for Ruby. You should probably
look into that as well.
Thanks for your help and sorry for my english, i hope it’s
understandable.
No problem.
Kind regards
robert