I am trying to create and edit a reg key in ruby but keep getting the following error:
setKeyStringValue error:
false
error in 'open' system cannot find file specified
My code:
require 'win32/registry'
$hkey_local_machine=Win32::Registry::HKEY_LOCAL_MACHINE
$hkey_current_user=Win32::Registry::HKEY_CURRENT_USER
# Returns the Microsoft Registry path to the Microsoft software information
def getKeyValue(hive, key_path, key_name)
reg_obj=hive.open(key_path, Win32::Registry::KEY_READ)
begin
reg_typ, reg_val = reg_obj.read(key_name)
rescue Win32::Registry::Error
puts "key not found : #{key_name}"
end
return reg_val
end
#used to set a String value for a key
def setKeyStringValue(hive,key_path, key_name, key_value)
begin
reg_key=hive.open(key_path, Win32::Registry::KEY_WRITE)
puts "opened key"
reg_key.write(key_name,Win32::Registry::REG_SZ,key_value)
rescue Win32::Registry::Error
puts "setKeyStringValue error:"
return false
end
return true
end
puts setKeyStringValue(Win32::Registry::HKEY_CURRENT_USER,"SOFTWARE\\PsychSoft","foo","woo")
puts getKeyValue(Win32::Registry::HKEY_CURRENT_USER,"SOFTWARE\\PsychSoft","foo")
Can someone explain why this code doesnt work?
I suppose your registry path needs to be enclosed in single '
Your code works like this
profiles_key = 'Software\Microsoft'
puts setKeyStringValue(Win32::Registry::HKEY_CURRENT_USER, profiles_key, "foo", "woo")
puts getKeyValue(Win32::Registry::HKEY_CURRENT_USER, profiles_key, "foo")
Which gives
opened key
true
woo
Related
I am writing a short ruby script that takes a file as an argument and then parses that file.
I have put together a few conditions in the initialize method to ensure that a file path exists and it is readable and if it nots it prints an error message to the user.
However when I run the file with out a file attached along side the message "please add log file path". I also receive the following error messages.
please add log file path
Traceback (most recent call last):
3: from webserver_log_parser.rb:41:in `<main>'
2: from webserver_log_parser.rb:41:in `new'
1: from webserver_log_parser.rb:6:in `initialize'
webserver_log_parser.rb:6:in `exist?': no implicit conversion of nil into String (TypeError)
I would be really grateful if someone could explain why this happens and a way to fix this issue.
def initialize(log_file_path = nil)
puts 'please add log file path' unless log_file_path
puts 'Could not find the file path' unless File.exist?(log_file_path)
puts '${log_file_path} is unreadable' unless File.readable?(log_file_path)
extract_log_file(log_file_path)
end
def extract_log_file(log_file_path)
webpages = Hash.new { |url, ip_address| url[ip_address] = [] }
File.readlines(log_file_path).each do |line|
url, ip_address = line.split
webpages[url] << ip_address
end
sort_results(webpages)
end
def sort_results(results)
total_views = {}
unique_views = {}
results.each do |url, ip_address|
total_views[url] = ip_address.length
unique_views[url] = ip_address.uniq.length
end
display_results(total_views, unique_views)
end
def display_results(views, unique_views)
puts 'The most viewed pages are as follows:'
total_views_sorted = views.sort_by { |_k, count| -count }
total_views_sorted.each { |key, count| puts "#{key} #{count}" }
puts 'The pages with the most unique views are as follows:'
unique_sort = unique_views.sort_by { |_k, count| -count }
unique_sort.each { |key, count| puts "#{key} #{count}" }
end
end
if $PROGRAM_NAME == __FILE__
LogParser.new(ARGV[0])
end```
If you want to directly terminate the script with a message, you can use abort.
def initialize(log_file_path = nil)
abort("please add log file path") unless log_file_path
abort("Could not find the file path") unless File.exist?(log_file_path)
abort("${log_file_path} is unreadable") unless File.readable?(log_file_path)
extract_log_file(log_file_path)
end
When your guard conditions are triggered, you need to stop further processing (no need to check for readability of a file at file_path if you already established that file_path is nil). It could look like this, for example:
def initialize(log_file_path = nil)
unless log_file_path
puts 'please add log file path'
return
end
unless File.exist?(log_file_path)
puts 'Could not find the file path'
return
end
unless File.readable?(log_file_path)
puts '${log_file_path} is unreadable'
return
end
extract_log_file(log_file_path)
end
I have a YAML file containing usernames and passwords.
Overview of YAML:
users:
test:
password: test
test2:
password: test2
I want to encrypt the password value into an MD5 hash using Digest::MD5 for example:
user:
Lost Bam:
password: testtesttest #<=I want to overwrite this password with a MD5 hash
In Digest is there a way to encrypt a hash value? If so how do I implement this into a YAML file?
md5.rb Source:
require 'yaml'
require 'digest'
private
def load_file
File.exist?('info.yml') ? YAML.load_file('info.yml') : {users: {}}
end
def read_file
File.read('info.yml')
end
def save_file( hash )
File.open('info.yml', 'w') { |f| f.write(hash.to_yaml)}
end
def add_user
hash = load_file
hash["users"][prompt('Enter username:')] =
{ "password" => prompt('Enter password:') }
puts "Encrypt information?"
information = gets.chomp
case input
when /yes/i
# hash = Digest::MD5.digest(["password"]'value')<-Doesn't work
#
#This is where I want to be able to encrypt the
#value of the password key that was entered by the user
#
# save_file( hash )
else
puts "Add another?"#Not completed yet
end
save_file( hash )
end
main.rb Source:
require_relative 'md5.rb'
def main
puts <<-END.gsub(/^\s*>/, '')
>
>To load information type "L" to quit system type "Q"
>
END
input = gets.chomp.upcase
case input
when "L"
add_user
when "Q"
exit_system
else
exit_lock
end
end
def exit_system
puts "Exiting..."
exit
end
def exit_lock
puts "Locked out, please contact system administrator"
exit
end
def restart
puts "Encrypt more?"
input = gets.chomp
if input =~ /yes/i
return true
else
exit_system
end
end
def prompt( message )
puts message
gets.chomp
end
main
You can use Digest::MD5:
require 'digest'
Digest::MD5.digest('value')
http://ruby-doc.org/stdlib-2.1.0/libdoc/digest/rdoc/Digest.html
I'm having trouble with this code (again).
I'm trying to get Ruby to check if tree is equal to any of the items in $do_not_scan and all I'm getting is a "cannot convert Array into String" error. Any way to fix such a thing?
My code:
#filesniffer by Touka, ©2015
$filecount = 0
$trees = Dir.entries("C:\\")
$do_not_scan = ["bootmgr", "BOOTNXT", "USER", ".", "Documents and Settings", "PerfLogs", "System Recovery", "System Volume Information", "$RECYCLE.BIN"]
def scan
$trees.each do |tree|
unless tree.include?($do_not_scan[0...8])
puts "scanning #{tree}"
entries = Dir.entries("c:\\#{tree}")
entries.each do |filename|
if filename == "**\*.dll"
puts "Found #{filename} in #{tree}"
end
end
end
end
end
def scan_loop
$trees.each do |tree|
scan
unless tree.include?($do_not_scan[0...8])
subtrees = Dir.entries("#{tree}")
subtrees.each do |tree|
scan
scan_loop
end
end
end
end
scan_loop
sleep
It looks like the following have to change in the scan and scan_loop methods:
$do_not_scan[0...8].include?(tree)
In place off:
tree.include?($do_not_scan[0...8])
I have created an decryption script using base64 to decrypt passwords with Chef databags that I have previously encrypted using a different script. The script for decryption complies without throwing any errors although it returns a junk string with strange symbols.
An example of encrypted string:
fff: T3UZSkX4vsJxnWEaIMWK3w==
When decoded:
ᄒヨ5pチᄒミᄒワᄒᆰ`ᄒᄆ,Chホᄌᄂ
The part of script I am using to decrypt is,
#Call decryption method
item = decryptDatabag(project, domain)
puts(item["chef_password"])
puts(item["Password"])
secret = Chef::EncryptedDataBagItem.load_secret("\\\\############\\ChefEncryptedDatabagKey\\#{#project}\\secret.txt") .
item = Chef::EncryptedDataBagItem.load(project, "EncryptedItem", secret)
It is also pulling from the file encrypted_data_bag_item.rb.
ALGORITHM = 'aes-256-cbc'
def [](key)
value = #enc_hash[key]
if key == "id" || value.nil?
value
else
self.class.decrypt(value, #secret)
end
end
def self.decrypt(value, key)
YAML.load(self.decipher(:decrypt, Base64.decode64(value), key))
end
def self.decipher(direction, data, key)
decipher = OpenSSL::Cipher::Cipher.new(ALGORITHM)
decipher.decrypt
decipher.padding = 0
decipher.send(direction)
decipher.pkcs5_keyivgen(key)
ans = decipher.update(data)
ans << decipher.final
ans
end
The part of script I am using to encrypt is,
#sourceDatabag = nil
#sourceItems = Hash.new
#sourceDatabag = #sourcerest.get_rest("/data/#{#databag}")
if #sourceDatabag.has_key?("EncryptedItem")
sourceItem = #sourcerest.get_rest("/data/#{#databag}/EncryptedItem")
targetItem = Chef::DataBagItem.new
targetItem.data_bag(#databag)
sourceItem.each do |key, value|
if value.end_with? ".lock"
print "#{#databag_name}: #{key} has already been encrypted!\n"
targetItem[key] = value
elsif key != "id"
targetItem[key] = Chef::EncryptedDataBagItem.encrypt_value(value, #databag)
puts "Encrypted the #{key} item, and saved Databag #{#databag}\n"
else
targetItem[key] = value
end
end
else
puts "EncryptedKey item not found, quitting"
exit(1)
end
return
rescue Net::HTTPServerException => hse
puts "The #{#databag} databag does not exist, please create one before running this job"
end
end
Can anyone help me with this problem please?
I need to create a script in ruby to get all the database objects (tables,views,sps, functions, etc) and be able to create files for each of the db objects.
I would like to be able to implement this solution in ruby and use some sort of Win32 class may be?.
I am using SQL Server 2008 R2. Not ruby on rails of course.
# == Name
# SQL Server Library
# == Author
# Maverick
# == Synopsis
# ADO SQL Server Library
# == Notes:
# Modify the following global variables in order to set up an execution environment
# sql_str: This is the SQL CMD command option and arguments -> Change the -U and -P arguments for -E to enable integrated security
# http://rubyonwindows.blogspot.com/2007/03/ruby-ado-and-sqlserver.html
Thread.abort_on_exception = true
require 'win32ole'
require 'win32api'
CoInitialize = Win32API.new('ole32', 'CoInitialize', 'P', 'L')
# This class manages database connection and queries
class SqlServer
attr_accessor :connection, :data, :fields
def initialize
#connection = nil
#data = nil
#cmd_time_out = 900
end
#opens a database connection using integrated security
def open(server,database)
connection_string = "Provider=SQLOLEDB.1;"
connection_string << "Persist Security Info=False;"
connection_string << "Integrated Security=SSPI;"
connection_string << "Initial Catalog=#{database};"
connection_string << "Data Source=#{server};"
connection_string << "Network Library=dbmssocn"
CoInitialize.call( 0 )
if server.eql?(nil) or database.eql?(nil) or server.eql?('') or database.eql?('') then
raise Exception, "Application Error: Server or Database parameters are missing"
end
begin
#connection = WIN32OLE.new('ADODB.Connection')
#connection.ConnectionString = connection_string
#connection.open
rescue Exception => e
#connection.Errors.Count.times { |x|
show_ado_error(#connection.Errors)
}
raise Exception, "Application Error: #{e.message} \n Can't open a connection with the server. Verify user credentials"
end
end
def get_connection
return #connection
end
#executes a query without returning any rows
def execute_non_query(query)
begin
command = WIN32OLE.new('ADODB.Command')
command.CommandType = 1
command.ActiveConnection = #connection
command.CommandText = query
command.CommandTimeOut = #cmd_time_out
result = command.Execute
if #connection.Errors.Count > 1 then
raise Exception,"ADODB Connection contains errors"
end
rescue Exception => e
show_ado_error(#connection.Errors)
raise Exception, "Application Error: #{e.message} \n Can't execute query. Verify sql syntax"
end
return result
end
#prints ado db errors using ado connection error property
def show_ado_error(obj)
obj.Count.times { |x|
puts "#{x}. ADODB Error Number: " + #connection.Errors(x).Number.to_s
puts "#{x}. ADODB Generated By: " + #connection.Errors(x).Source
puts "#{x}. ADODB SQL State: " + #connection.Errors(x).SQLState
puts "#{x}. ADODB Native Error: " + #connection.Errors(x).NativeError.to_s
puts "#{x}. ADODB Description: " + #connection.Errors(x).Description
}
end
#executes a query returning an array of rows
def execute_query(sql_query)
# Create an instance of an ADO Record set
begin
record_set = WIN32OLE.new('ADODB.Recordset')
# Open the record set, using an SQL statement and the
# existing ADO connection
record_set.open(sql_query, #connection)
# Create and populate an array of field names
#fields = []
record_set.fields.each do |field|
#fields << field.Name
end
begin
# Move to the first record/row, if any exist
record_set.movefirst
# Grab all records
#data = record_set.getrows
rescue
#data = []
end
record_set.close
# An ADO Recordset's GetRows method returns an array
# of columns, so we'll use the transpose method to
# convert it to an array of rows
#data = #data.transpose
rescue
raise Exception, "Application Error: Can't execute query. Verify SQL Query syntax"
end
end
def close
#connection.Close
end
end