Class: Inspec::Resources::MysqlSession

Inherits:
Object
  • Object
show all
Defined in:
lib/resources/mysql_session.rb

Instance Method Summary collapse

Constructor Details

#initialize(user = nil, pass = nil, host = 'localhost', port = nil, socket = nil) ⇒ MysqlSession

Returns a new instance of MysqlSession.



18
19
20
21
22
23
24
25
26
# File 'lib/resources/mysql_session.rb', line 18

def initialize(user = nil, pass = nil, host = 'localhost', port = nil, socket = nil)
  @user = user
  @pass = pass
  @host = host
  @port = port
  @socket = socket
  init_fallback if user.nil? or pass.nil?
  skip_resource("Can't run MySQL SQL checks without authentication") if @user.nil? or @pass.nil?
end

Instance Method Details

#query(q, db = '') ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/resources/mysql_session.rb', line 28

def query(q, db = '')
  # TODO: simple escape, must be handled by a library
  # that does this securely
  escaped_query = q.gsub(/\\/, '\\\\').gsub(/"/, '\\"').gsub(/\$/, '\\$')

  # run the query
  command = "mysql -u#{@user} -p#{@pass}"
  if !@socket.nil?
    command += " -S #{@socket}"
  else
    command += " -h #{@host}"
  end
  command += " --port #{@port}" unless @port.nil?
  command += " #{db} -s -e \"#{escaped_query}\""

  cmd = inspec.command(command)
  out = cmd.stdout + "\n" + cmd.stderr
  if out =~ /Can't connect to .* MySQL server/ || out.downcase =~ /^error/
    # skip this test if the server can't run the query
    warn("Can't connect to MySQL instance for SQL checks.")
  end

  # return the raw command output
  cmd
end

#to_sObject



54
55
56
# File 'lib/resources/mysql_session.rb', line 54

def to_s
  'MySQL Session'
end