user3219834
user3219834

Reputation: 37

How do I delete a hash out of an array in Ruby?

The big picture is, I am taking the code below, which produces something like a windows tasklist. but I want to filter out the users system, local service and network service. then filter out the columns arch, session and path.

print_line
processes = @client.sys.process.get_processes
process_list = processes.to_table('Header' => "%bld %dmag Target Process Info:\n", 'Indent' => 4)

so far i got the users out, but im stuck on removing the hashes with the keys arch session and path. here is the output in raw format.

[
  {"pid"=>0, "ppid"=>0, "name"=>"[System Process]", "path"=>"", "session"=>4294967295, "user"=>"", "arch"=>""}, 
  {"pid"=>456, "ppid"=>320, "name"=>"explorer.exe", "path"=>"C:\\WINDOWS\\Explorer.EXE", "session"=>0, "user"=>"CLINE\\Administrator", "arch"=>"x86"}, 
  {"pid"=>544, "ppid"=>204, "name"=>"TPAutoConnect.exe", "path"=>"C:\\Program Files\\VMware\\VMware Tools\\TPAutoConnect.exe", "session"=>0, "user"=>"CLINE\\Administrator", "arch"=>"x86"}, 
  {"pid"=>1096, "ppid"=>456, "name"=>"vmtoolsd.exe", "path"=>"C:\\Program Files\\VMware\\VMware Tools\\vmtoolsd.exe", "session"=>0, "user"=>"CLINE\\Administrator", "arch"=>"x86"}, 
  {"pid"=>180, "ppid"=>456, "name"=>"rundll32.exe", "path"=>"C:\\WINDOWS\\system32\\rundll32.exe", "session"=>0, "user"=>"CLINE\\Administrator", "arch"=>"x86"}, 
  {"pid"=>1208, "ppid"=>724, "name"=>"logon.scr", "path"=>"C:\\WINDOWS\\System32\\logon.scr", "session"=>0, "user"=>"CLINE\\Administrator", "arch"=>"x86"}
]

Here is my code so far.

print_line
processes = @client.sys.process.get_processes
blacklist = ["NT AUTHORITY\\SYSTEM", "NT AUTHORITY\\LOCAL SERVICE", "NT AUTHORITY\\NETWORK SERVICE"]
filtered = processes.reject {|h| blacklist.include? h['user']}
print_status (filtered)

also the original had the output using the to_table but I seemed to have broke that?

Upvotes: 0

Views: 76

Answers (2)

CuriousMind
CuriousMind

Reputation: 34135

so, My Understanding is that you want

pid, ppid, name, user.

Using ActiveSupport, you can just slice them in-place:

processes = @client.sys.process.get_processes
blacklist = ["NT AUTHORITY\\SYSTEM", "NT AUTHORITY\\LOCAL SERVICE", "NT AUTHORITY\\NETWORK SERVICE"]
filtered = processes.map!{|i| i.slice!("pid", "ppid", "name", "user")}.reject {|h| blacklist.include? h['user']}
print_status (filtered)

Is what you are trying to do?

Upvotes: 1

Arie Xiao
Arie Xiao

Reputation: 14082

Use Hash#reject to delete key-value pairs that satisfy some condition from a Hash to get a new Hash.

filtered.map{|p| p.reject{|k, _| %w(arch session path).include?(k)} }

Other options are Hash#reject!, Hash#delete

Upvotes: 0

Related Questions