diff --git a/lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb b/lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb index fd9342b159..73df8443ee 100644 --- a/lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb +++ b/lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb @@ -290,6 +290,25 @@ class File < Rex::Post::Meterpreter::Extensions::Stdapi::Fs::IO end end + # + # With no associated block, File.open is a synonym for ::new. If the optional + # code block is given, it will be passed the opened file as an argument, and + # the File object will automatically be closed when the block terminates. In + # this instance, File.open returns the value of the block. + # + # (doc stolen from http://www.ruby-doc.org/core-1.9.3/File.html#method-c-open) + # + def File.open(name, mode="r", perms=0) + f = new(name, mode, perms) + if block_given? + ret = yield f + f.close + return ret + else + return f + end + end + ## # # Constructor diff --git a/test/modules/post/test/meterpreter.rb b/test/modules/post/test/meterpreter.rb index e21066d4f1..1e74ef80fa 100644 --- a/test/modules/post/test/meterpreter.rb +++ b/test/modules/post/test/meterpreter.rb @@ -199,16 +199,16 @@ class Metasploit4 < Msf::Post it "should create and remove files" do res = true - fd = session.fs.file.new("meterpreter-test", "wb") - fd.write("test") - fd.close + res &&= session.fs.file.open("meterpreter-test", "wb") { |fd| + fd.write("test") + } vprint_status("Wrote to meterpreter-test, checking contents") - fd = session.fs.file.new("meterpreter-test", "rb") - contents = fd.read - vprint_status("Wrote #{contents}") - res &&= (contents == "test") - fd.close + res &&= session.fs.file.open("meterpreter-test", "rb") { |fd| + contents = fd.read + vprint_status("Wrote #{contents}") + (contents == "test") + } session.fs.file.rm("meterpreter-test") res &&= !session.fs.dir.entries.include?("meterpreter-test")