Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 12 total  RSS 

Get uptime of remote computer using WMI

// description of your code here
Get uptime of remote computer using WMI, I'm not sure the convert time function is correct, it gives different results than psinfo.exe

Private Function GetUptime() As String


        Dim WMIScope As Management.ManagementScope
        Dim WMIConnectionOptions As New Management.ConnectionOptions
        Dim strRootDomain As String
        Dim objRootLDAP As DirectoryEntry
        Dim query As ManagementObjectSearcher
        Dim queryCollection As ManagementObjectCollection
        Dim oq As New System.Management.ObjectQuery
        Dim mo As New ManagementObject
        Dim perftimestamp As String = ""
        Dim perttimefreq As String = ""
        Dim counter As String = ""
        Dim iUptimeInSec As Long = 0

        With WMIConnectionOptions
            .Impersonation = System.Management.ImpersonationLevel.Impersonate
            .Authentication = System.Management.AuthenticationLevel.Packet

        End With

        WMIScope = New Management.ManagementScope("\\" & _
        Strcomputer & "\root\cimv2", WMIConnectionOptions)

        objRootLDAP = New DirectoryEntry("LDAP://RootDSE")
        strRootDomain = objRootLDAP.Properties.Item("rootDomainNamingContext").Value.ToString

        oq = New System.Management.ObjectQuery("select * from Win32_PerfRawData_PerfOS_System")
        query = New ManagementObjectSearcher(WMIScope, oq)
        queryCollection = query.Get()

        For Each oReturn As ManagementObject In queryCollection
            perftimestamp = oReturn("Timestamp_Object").ToString()
            perttimefreq = oReturn("Frequency_Object").ToString()
            counter = oReturn("SystemUpTime").ToString()
        Next

        ' Calculation in seconds:
        iUptimeInSec = Convert.ToInt64((Double.Parse(perftimestamp) - Double.Parse(counter)) / Double.Parse(perttimefreq))

        ' convert the seconds
        Return ConvertTime(iUptimeInSec)

    End Function

    Private Function ConvertTime(ByVal seconds As Long) As String

        Dim ConvSec As Long
        Dim ConvMin As Long
        Dim ConvHour As Long
        Dim ConvDays As Long

        Math.DivRem(seconds, 60, ConvSec)

        Math.DivRem(seconds, 3600, ConvMin)
        ConvMin = ConvMin / 60

        Math.DivRem(seconds, (3600 * 24), ConvHour)
        ConvHour = ConvHour / 3600

        ConvDays = (seconds / (3600 * 24))

        Return (ConvDays.ToString() + " days " + ConvHour.ToString() + " hours " + ConvMin.ToString() + " minutes " + ConvSec.ToString() + " seconds ")

    End Function

'or you could try this method which still doesn't match psinfo or systeminfo but it is closer

Private Function GetUptime2() As String

        Dim WMIScope As Management.ManagementScope
        Dim WMIConnectionOptions As New Management.ConnectionOptions
        Dim strRootDomain As String
        Dim objRootLDAP As DirectoryEntry
        Dim query As ManagementObjectSearcher
        Dim queryCollection As ManagementObjectCollection
        Dim oq As New System.Management.ObjectQuery
        Dim mo As New ManagementObject
        Dim perftimestamp As String = ""
        Dim perttimefreq As String = ""
        Dim counter As String = ""
        Dim iUptimeInSec As Long = 0
        Dim LastBootUpTime As DateTime
        Dim dateNow As DateTime = Date.Now

        With WMIConnectionOptions
            .Impersonation = System.Management.ImpersonationLevel.Impersonate
            .Authentication = System.Management.AuthenticationLevel.Packet

        End With

        WMIScope = New Management.ManagementScope("\\" & _
        Strcomputer & "\root\cimv2", WMIConnectionOptions)

        objRootLDAP = New DirectoryEntry("LDAP://RootDSE")
        strRootDomain = objRootLDAP.Properties.Item("rootDomainNamingContext").Value.ToString

        oq = New System.Management.ObjectQuery("Select * from Win32_OperatingSystem")

        query = New ManagementObjectSearcher(WMIScope, oq)
        queryCollection = query.Get()

        For Each oReturn As ManagementObject In queryCollection

            LastBootUpTime = System.Management.ManagementDateTimeConverter.ToDateTime(oReturn("LastBootUpTime").ToString)
            
        Next

        Dim ts As TimeSpan = dateNow.Subtract(LastBootUpTime)
        Console.WriteLine(ts.Days.ToString + " days " + ts.Hours.ToString + " hours " + ts.Minutes.ToString + " minutes " + ts.Seconds.ToString + " seconds ")

    End Function

Get the username of the logged on user on remote machine

// description of your code here
Cheats a little by getting the owner of explorer.exe to derive the logged in user. Add reference to System.Management and I think DirectoryServices
Imports System.Management
Imports System.DirectoryServices
Imports Microsoft.Win32
Imports System.Runtime.InteropServices
Module Module1
    Dim objManagementClass As ManagementClass
    Dim objManagementScope As ManagementScope
    Dim objManagementBaseObject As ManagementBaseObject
    Sub Main()

        Dim WMIScope As Management.ManagementScope
        Dim WMIConnectionOptions As New Management.ConnectionOptions
        Dim strRootDomain As String
        Dim objRootLDAP As DirectoryEntry
        Dim query As ManagementObjectSearcher
        Dim queryCollection As ManagementObjectCollection
        Dim oq As New System.Management.ObjectQuery
        Dim mo As New ManagementObject
        Dim UserDomain As String
        Dim UserID As String
        Dim StrLoggedUserSID() As Byte

        Dim Strcomputer As String = My.Application.CommandLineArgs.Item(0)
        'Console.WriteLine(Strcomputer)

        With WMIConnectionOptions
            .Impersonation = System.Management.ImpersonationLevel.Impersonate
            .Authentication = System.Management.AuthenticationLevel.Packet

        End With

        WMIScope = New Management.ManagementScope("\\" & _
        strcomputer & "\root\cimv2", WMIConnectionOptions)

        objRootLDAP = New DirectoryEntry("LDAP://RootDSE")
        strRootDomain = objRootLDAP.Properties.Item("rootDomainNamingContext").Value.ToString

        oq = New System.Management.ObjectQuery("SELECT * from Win32_process Where Name='explorer.exe' and SessionID=0")
        query = New ManagementObjectSearcher(WMIScope, oq)
        queryCollection = query.Get()

        If queryCollection.Count = 0 Then
            Console.WriteLine("No user logged on")
            Exit Sub
        Else

            Dim strKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon"
            objManagementScope = New ManagementScope
            objManagementScope.Path.Server = strcomputer
            objManagementScope.Path.NamespacePath = "root\default"
            objManagementScope.Options.EnablePrivileges = True
            objManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate
            objManagementScope.Connect()

            objManagementClass = New ManagementClass("stdRegProv")
            objManagementClass.Scope = objManagementScope
            objManagementBaseObject = objManagementClass.GetMethodParameters("EnumValues")
            objManagementBaseObject.SetPropertyValue("hDefKey", CType("&H" & Hex(RegistryHive.LocalMachine), Long))
            objManagementBaseObject.SetPropertyValue("sSubKeyName", strKeyPath)

            UserDomain = CStr(GetRegValues("DefaultDomainName", strKeyPath, "HKLM"))
            UserID = CStr(GetRegValues("DefaultUserName", strKeyPath, "HKLM"))

            Console.WriteLine(UserID)

            'If the SID or the full name is needed sometime in the future the code is below

            'If UCase(UserDomain) = UCase(strcomputer) Then
            'Console.WriteLine("Logged on user = " & UserDomain & "\" & UserID & " (local user)")
            'Exit Sub
            'End If

            'Dim LdapBind As String
            'LdapBind = ("LDAP://" & strRootDomain)

            'Dim deEntry3 As New DirectoryEntry(LdapBind)
            'Dim DSearch As New DirectorySearcher(deEntry3)

            'With DSearch
            '    .SearchScope = SearchScope.Subtree
            '    .Filter = "(&(objectclass=user)(sAMAccountName=" & UserID & "))"
            '    .PropertiesToLoad.Add("name")
            '    .PropertiesToLoad.Add("sAMAccountName")
            '    .PropertiesToLoad.Add("distinguishedName")
            'End With

            'Dim sResultSet As SearchResult

            'For Each sResultSet In DSearch.FindAll()

            '    If UCase(GetProperty(sResultSet, "sAMAccountName")) = UCase(UserID) Then

            '        Console.WriteLine("Logged on user = " & GetProperty(sResultSet, "name") & " (as " & _
            '        UserDomain & "\" & UserID & ")")

            '        Dim deEntry4 As New DirectoryEntry("LDAP://" & GetProperty(sResultSet, "distinguishedName").ToString)
            '        StrLoggedUserSID = CType(deEntry4.Properties("objectSid").Value, Byte())
            '        Console.WriteLine("User's SID = " & ConvertSid(StrLoggedUserSID))
            '    End If
            'Next

        End If
    End Sub

    Public Function GetProperty(ByVal srSearchResult As SearchResult, ByVal strPropertyName As String) As String
        If srSearchResult.Properties.Contains(strPropertyName) Then
            Return srSearchResult.Properties(strPropertyName)(0).ToString()
        Else
            Return String.Empty
        End If
    End Function
    Private Function GetRegValues(ByVal regkeyValue As String, ByVal regkey As String, ByVal Hive As String)

        Select Case Hive
            Case "HKLM"
                Hive = CStr(RegistryHive.LocalMachine)
            Case "HKU"
                Hive = CStr(RegistryHive.Users)
            Case "HKCU"
                Hive = CStr(RegistryHive.CurrentUser)
            Case "HKCR"
                Hive = CStr(RegistryHive.ClassesRoot)
        End Select

        objManagementBaseObject = objManagementClass.GetMethodParameters("GetStringValue")
        objManagementBaseObject.SetPropertyValue("hDefKey", CType("&H" & Hex(Hive), Long))
        objManagementBaseObject.SetPropertyValue("sSubKeyName", regkey)
        objManagementBaseObject.SetPropertyValue("sValueName", regkeyValue)
        objManagementBaseObject = objManagementClass.InvokeMethod("GetStringValue", objManagementBaseObject, Nothing)
        GetRegValues = objManagementBaseObject("sValue")

    End Function

    Public Function ConvertSid(ByVal sid As Byte()) As String

        Dim sidString As String
        Dim sidPtr As IntPtr
        Dim sidStringPtr As IntPtr
        Dim res As Integer

        sidPtr = Marshal.AllocHGlobal(sid.Length)
        Marshal.Copy(sid, 0, sidPtr, sid.Length)
        res = ConvertSidToStringSid(sidPtr, sidStringPtr)
        If res = 0 Then
            Throw New System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error())
        End If
        sidString = Marshal.PtrToStringAuto(sidStringPtr)
        Marshal.FreeHGlobal(sidPtr)
        Marshal.FreeHGlobal(sidStringPtr)

        Return sidString

    End Function

    <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
    Private Function ConvertSidToStringSid(ByVal pSID As IntPtr, ByRef pSidString As IntPtr) As Integer
    End Function

End Module

Make a remote URL work like a file upload (in Rails)

Want to load a remote URL into an acts_as_attachment/attachment_fu model? Use this little utility class.

  class UrlUpload
    EXTENSIONS = {
      "image/jpeg" => ["jpg", "jpeg", "jpe"],
      "image/gif" => ["gif"],
      "image/png" => ["png"]
    }
    attr_reader :original_filename, :attachment_data
    def initialize(url)
      @attachment_data = open(url)
      @original_filename = determine_filename
    end

    # Pass things like size, content_type, path on to the downloaded file
    def method_missing(symbol, *args)
      if self.attachment_data.respond_to? symbol
        self.attachment_data.send symbol, *args
      else
        super
      end
    end
    
    private
      def determine_filename
        # Grab the path - even though it could be a script and not an actual file
        path = self.attachment_data.base_uri.path
        # Get the filename from the path, make it lowercase to handle those
        # crazy Win32 servers with all-caps extensions
        filename = File.basename(path).downcase
        # If the file extension doesn't match the content type, add it to the end, changing any existing .'s to _
        filename = [filename.gsub(/\./, "_"), EXTENSIONS[self.content_type].first].join(".") unless EXTENSIONS[self.content_type].any? {|ext| filename.ends_with?("." + ext) }
        # Return the result
        filename
      end
  end


Now when you have the URL you want to load, do something like this:

@model.uploaded_data = UrlUpload.new(url)


Or better yet, make a pseudo-accessor on your aaa/attachment_fu model so you can stay "model-heavy".

def url=(value)
  self.uploaded_data = UrlUpload.new(value)
end

DB2 Federation

Server A configuration:
OS: WinXP
Instance name: TMINST
Instance user and password: db2admin/db2admin
Required nickname for remote table: DB2ADMIN.R_CUSTOMERS

Server B configuration:
OS: Linux
IP: 10.60.100.21
DB2 service port: 50000
Instance user and password: db2inst1/db2inst1
Database name: TM_ON
Table name to be linked: CUSTOMERS

CLP Commands @Server A:
db2set DB2INSTDEF=TMINST
SET DB2INSTANCE=TMINST
db2 UPDATE DATABASE MANAGER CONFIGURATION USING FEDERATED YES IMMEDIATE
db2 CATALOG TCPIP NODE RTMINST REMOTE 10.60.100.21 SERVER 50000 REMOTE_INSTANCE db2inst1 OSTYPE Linux
db2 CATALOG DATABASE TM_ON AS RTM_ON AT NODE RTMINST 
db2start
db2 CONNECT TO TM_ON USER db2admin USING db2admin
db2 CREATE WRAPPER DRDA
db2 "CREATE SERVER RTM_ON TYPE DB2/UDB VERSION '9.1' WRAPPER DRDA AUTHORIZATION \"db2inst1\" PASSWORD \"db2inst1\" OPTIONS( ADD DBNAME 'RTM_ON')"
db2 CREATE USER MAPPING FOR DB2ADMIN SERVER RTM_ON OPTIONS ( ADD REMOTE_AUTHID 'db2inst1', ADD  REMOTE_PASSWORD 'db2inst1') 
db2 CREATE NICKNAME DB2ADMIN.R_CUSTOMERS FOR RTM_ON.DB2INST1.CUSTOMERS
db2 SELECT * FROM R_CUSTOMERS

HTTPRequest //JavaScript Class


Class to make remote requests, which can be used on the popular "AJAX".

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/http-request [v1.0]

HTTPRequest = function(){};
with({$: HTTPRequest.prototype}){
	$.isSupported = function(){
		return !!this.getConnection();
	};
	$.events = ["start", "open", "send", "load", "end"];
	$.filter = encodeURIComponent;
	$.getConnection = function(){
		var i, o = [function(){return new ActiveXObject("Msxml2.XMLHTTP");},
		function(){return new ActiveXObject("Microsoft.XMLHTTP");},
		function(){return new XMLHttpRequest;}];
		for(i = o.length; i--;) try{return o[i]();} catch(e){}
		return null;
	};
	$.formatParams = function(params){
		var i, r = [];
		for(i in params) r[r.length] = i + "=" + (this.filter ? this.filter(params[i]) : params[i]);
		return r.join("&");
	};
	$.get = function(url, params, handler, waitResponse){
		return this.request("GET", url + (url.indexOf("?") + 1 ? "&" : "?") + this.formatParams(params), null, handler, null, waitResponse);
	};
	$.post = function(url, params, handler, waitResponse){
		return this.request("POST", url, params = this.formatParams(params), handler, {
			"Connection": "close",
			"Content-Length": params.length,
			"Method": "POST " + url + " HTTP/1.1",
			"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
		}, waitResponse);
	};
	$.request = function(method, url, params, handler, headers, waitResponse){
		var i, o = this.getConnection(), f = handler instanceof Function;
		try{
			o.open(method, url, !waitResponse);
			waitResponse || (o.onreadystatechange = function(){
				var s = $.events[o.readyState];
				f ? handler(o) : s in handler && handler[s](o);
			});
			o.setRequestHeader("HTTP_USER_AGENT", "XMLHttpRequest");
			for(i in headers)
				o.setRequestHeader(i, headers[i]);
			o.send(params);
			waitResponse && (f ? handler(o) : handler["end"] && handler["end"](o));
			return true;
		}
		catch(e){
			return false;
		}
	};
}


Example

<fieldset>
	<legend>HTTPRequest example</legend>
	<input type="button" value="POST request with generic listener and params passage" onclick="genericHandler()" />
	<br /><input type="button" value="GET request with specific listener (binded on load and end)" onclick="specificHandler()" />

<script type="text/javascript">
//<![CDATA[

var r = new HTTPRequest;

function myHandler(o){
	alert("Current event = " + r.events[o.readyState] +
	"\nAvailable \"responseText.length\" = " + o.responseText.length);
}
function genericHandler(){
	r.post(location.href, {param: "abcde", name: "Jonas", site: "http://jsfromhell.com"}, myHandler);
}
function specificHandler(){
	r.get(location.href, null, {"load": myHandler, "end": myHandler});
}
document.write(
	"<br />Supports XMLHTTPRequest = ".bold() + r.isSupported(),
	"<br />Encoded with the default filter (\"encodeURIComponent\") = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"})
);

r.filter = escape;
document.write("<br />Encoded with \"escape\" filter = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"}));

r.filter = null;
document.write("<br />Encoded with no filtering = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"}));

//]]>
</script>
</fieldset>

Grab HTML From Sites and Echo Results

Grabs specified tags from any url on the net and then echos each of the results on a seperate line, you then have the option to remove the tags from the echoed results.

<?php

$config['url']       = "http://www.business-tycoon.com"; // url of html to grab
$config['start_tag'] = "<b>"; // where you want to start grabbing
$config['end_tag']   = "</b>"; // where you want to stop grabbing
$config['show_tags'] = 0; // do you want the tags to be shown when you show the html? 1 = yes, 0 = no

class grabber
{
	var $error = '';
	var $html  = '';
	
	function grabhtml( $url, $start, $end )
	{
		$file = file_get_contents( $url );
		
		if( $file )
		{
			if( preg_match_all( "#$start(.*?)$end#s", $file, $match ) )
			{				
				$this->html = $match;
			}
			else
			{
				$this->error = "Tags cannot be found.";
			}
		}
		else
		{
			$this->error = "Site cannot be found!";
		}
	}
	
	function strip( $html, $show, $start, $end )
	{
		if( !$show )
		{
			$html = str_replace( $start, "", $html );
			$html = str_replace( $end, "", $html );
			
			return $html;
		}
		else
		{
			return $html;
		}
	}
}

$grab = new grabber;
$grab->grabhtml( $config['url'], $config['start_tag'], $config['end_tag'] );

echo $grab->error;

foreach( $grab->html[0] as $html )
{
	echo htmlspecialchars( $grab->strip( $html, $config['show_tags'], $config['start_tag'], $config['end_tag'] ) ) . "<br>";
}

?>

link_to_remote_unless_current

// Full discussion about this available at:
// http://6brand.com/articles/2006/06/07/link_to_remote_unless_current

# throw this in one of your controller helpers.
# it works just like a combination of link_to_unless_current and link_to_remote
def link_to_remote_unless_current(name, options = {}, html_options = {}, *parameters_for_method_reference, &block)
  if current_page?(options[:url])
    if block_given?
      block.arity <= 1 ? yield(name) : yield(name, remote_function(options), html_options, *parameters_for_method_reference)
    else
      name
    end
  else
    link_to_function(name, remote_function(options), html_options)
  end
end

A Client For the XML-RPC Servlet

// When combined with the Apache XML-RPC library this code
// will let you call the servlet in the snippet "An XML-RPC
// Servlet". Of course, since XML-RPC is pretty ubiquitous
// you can also use this code to call servers in dozens of
// other languages as well.

import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcClient;

public class XMLRPCTestClient {
    private static final String serverAddress = 
	"http://localhost:8080/lol/remoteapi";
    private static Log log = LogFactory.getLog(XMLRPCTestClient.class);
    
    /** Creates a new instance of XMLRPCTestClient */
    public XMLRPCTestClient(String address) {
        try {
            XmlRpcClient xmlrpc = new XmlRpcClient(address);

            Vector params = new Vector();
            params.addElement("Hello World! Hello!");

            try {
                // this method returns a string
                String result = (String) xmlrpc.execute("echo.echo", params);
                System.out.println(result);
            } catch (Exception e) {
                log.error("The remote procedure call failed.", e);
            }
        } catch (java.net.MalformedURLException mue) {
            log.error(
                "The address given for the XML-RPC interface is bad: " + address);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        XMLRPCTestClient xmlRPCTestClient = new XMLRPCTestClient(
            serverAddress);
    }
}

An XML-RPC Servlet

// This depends upon the Apache XML-RPC library.

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcServer;

public class XmlRpcServlet extends HttpServlet {
    public class EchoHandler {
        public String echo(String input) {
            return input;
        }
    }
	
    private XmlRpcServer server = new XmlRpcServer();

    private static Log log = LogFactory.getLog(XmlRpcServlet.class);

	@Override
	public void init(ServletConfig config) throws ServletException {
        server.addHandler("echo", new EchoHandler());
	}

	@Override
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
        byte[] result = server.execute(request.getInputStream());
        
        response.setContentType("text/xml");
        response.setContentLength(result.length);
        
        OutputStream output = response.getOutputStream();
        output.write(result);
        output.flush();
    }
}


// The following needs to be added to your web.xml file to
// expose the servlet so it may be called remotely.
  <servlet>
    <servlet-name>XmlRpcServlet</servlet-name>
    <servlet-class>XmlRpcServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>XmlRpcServlet</servlet-name>
    <url-pattern>/remoteapi</url-pattern>        
  </servlet-mapping>    

ssh remote backups

// http://www.linux.com/article.pl?sid=06/01/12/1937210
// Backup with remote compression and storage

// When compression is necessary (and feasible), workload
// distribution becomes more effective with OpenSSH. Just as // distcc allows multiple machines to compile
// simultaneously, OpenSSH lets one system create the
// archive, while another system compresses it:

// tar cf - dirname | ssh remotehost "gzip -c >
// ${TMPFILE}.tar.gz"

tar cf - local-dir-eliotwalker | ssh -l mctt remote-glos.corruptive.co.uk "gzip -c > corr.tar.gz"
« Newer Snippets
Older Snippets »
Showing 1-10 of 12 total  RSS