Monday, October 3, 2011

How to execute a remote command in IronRuby


def execute_remote_command(command, machine_name, username, password)
 begin
 require "System"
 windir = System::Environment.GetFolderPath(System::Environment::SpecialFolder.Windows)
 Dir.chdir "#{windir}\\Microsoft.NET\\Framework\\v4.0.30319\\"
 require 'System.Management'
        
 options = System::Management::ConnectionOptions.new()
 options.Username = username
 options.Password = password


 path = System::Management::ManagementPath.new("\\\\#{machine_name}\\root\\cimv2:Win32_Process")
 scope = System::Management::ManagementScope.new(path, options)


 scope.Connect()


 opt = System::Management::ObjectGetOptions.new()
 class_instance = System::Management::ManagementClass.new(scope, path, opt)


 in_params = class_instance.GetMethodParameters("Create")
 in_params["CommandLine"] = command


 # Execute the method and obtain the return values.
 out_params = class_instance.InvokeMethod("Create", in_params, nil)
 return out_params["returnValue"]
rescue Exception => ex
 puts ex.ToString()
 return "-1"
 end
# Return values:
# 0 Successful completion 
# 2 Access denied 
# 3 Insufficient privilege 
# 8 Unknown failure 
# 9 Path not found 
# 21 Invalid parameter
# -1 Other exception
end