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

About this user

Michael Ellerbeck http://mellerbeck.blogspot.com/

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

Get username of logged in remote user, vb.net Win32_ComputerSystem Version

// description of your code here
This is an even shorter method of getting the remote user through WMI
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
    Public Strcomputer As String = ""
    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

        Try

            Dim Strcomputer As String = My.Application.CommandLineArgs.Item(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 UserName from Win32_ComputerSystem")
            query = New ManagementObjectSearcher(WMIScope, oq)
            queryCollection = query.Get()

            For Each oReturn As ManagementObject In queryCollection

                If Not oReturn("UserName") Is Nothing Then
                    Console.WriteLine(oReturn("UserName").ToString)
                Else
                    Console.WriteLine("Not logged in")
                End If

            Next

        Catch ex As Exception

            Console.WriteLine(ex.ToString)

        End Try

    End Sub

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

Pulling allday events from the public calendar of an exchange 2003 server vb.net webdav

// description of your code here
This is code that pulls all day events from an exchange 2003 server using webdav.
Dim Request As System.Net.HttpWebRequest
        Dim Response As System.Net.HttpWebResponse
        Dim MyCredentialCache As System.Net.CredentialCache
        Dim strPassword As String
        Dim strDomain As String
        Dim strUserName As String
        Dim strCalendarURI As String
        Dim strQuery As String
        Dim bytes() As Byte
        Dim RequestStream As System.IO.Stream
        Dim ResponseStream As System.IO.Stream
        Dim ResponseXmlDoc As System.Xml.XmlDocument
        Dim HrefNodes As System.Xml.XmlNodeList
        Dim SizeNodes As System.Xml.XmlNodeList
        Dim SubjectNodeList As System.Xml.XmlNodeList
        Dim LocationNodeList As System.Xml.XmlNodeList
        Dim StartTimeNodeList As System.Xml.XmlNodeList
        Dim EndTimeNodeList As System.Xml.XmlNodeList
        Dim BusyStatusNodeList As System.Xml.XmlNodeList
        Dim InstanceTypeNodeList As System.Xml.XmlNodeList
        Dim output As String = ""

        Try
            ' Initialize variables.
            strUserName = "user"
            strPassword = "password"
            strDomain = "domain"
            
            strCalendarURI = "http://mail-server/public/Office Calendar/"

            Dim ddate As DateTime = Today

            Dim sStartTime As String = String.Format("{0:yyyy/MM/dd}", ddate) & " 07:00:00' "
            Dim sEndTime As String = String.Format("{0:yyyy/MM/dd}", ddate.AddDays(1)) & " 07:00:00' "

            strQuery = "<?xml version=""1.0""?>" & _
                   "<g:searchrequest xmlns:g=""DAV:"">" & _
                   "<g:sql>SELECT ""urn:schemas:calendar:alldayevent"", ""urn:schemas:calendar:location"", ""urn:schemas:httpmail:subject"", " & _
                   """urn:schemas:calendar:dtstart"", ""urn:schemas:calendar:dtend"", " & _
                   """urn:schemas:calendar:busystatus"", ""urn:schemas:calendar:instancetype"" " & _
                   "FROM Scope('SHALLOW TRAVERSAL OF """ & strCalendarURI & """') " & _
                   "WHERE ""DAV:contentclass"" = 'urn:content-classes:appointment' " & _
                   "AND ""urn:schemas:calendar:alldayevent"" = TRUE " & _
                   "AND ""urn:schemas:calendar:dtstart"" &lt;= '" & sStartTime & _
                    "AND ""urn:schemas:calendar:dtend"" &gt;= '" & sEndTime & _
                    "ORDER BY ""urn:schemas:calendar:dtstart"" ASC" & _
                   "</g:sql></g:searchrequest>"



            MyCredentialCache = New System.Net.CredentialCache
            MyCredentialCache.Add(New System.Uri(strCalendarURI), _
                "NTLM", _
                New System.Net.NetworkCredential(strUserName, strPassword, strDomain) _
                )

            ' Create the PUT HttpWebRequest object.
            Request = CType(System.Net.WebRequest.Create(strCalendarURI), _
                            System.Net.HttpWebRequest)

            ' Add the network credentials to the request.
            Request.Credentials = MyCredentialCache

            ' Specify the SEARCH method.
            Request.Method = "SEARCH"

            ' Encode the body using UTF-8.
            bytes = System.Text.Encoding.UTF8.GetBytes(strQuery)

            ' Set the content header length.  This must be
            ' done before writing data to the request stream.
            Request.ContentLength = bytes.Length

            ' Get a reference to the request stream.
            RequestStream = Request.GetRequestStream()

            ' Write the message body to the request stream.
            RequestStream.Write(bytes, 0, bytes.Length)

            ' Close the Stream object to release the connection
            ' for further use.
            RequestStream.Close()

            ' Set the Content Type header.
            Request.ContentType = "text/xml"

            ' Set the Translate header.
            Request.Headers.Add("Translate", "F")

            ' Send the SEARCH method request and get the
            ' response from the server.
            Response = CType(Request.GetResponse(), System.Net.HttpWebResponse)

            ' Get the XML response stream.
            ResponseStream = Response.GetResponseStream()

            ' Create the XmlDocument object from the XML response stream.
            ResponseXmlDoc = New System.Xml.XmlDocument
            ResponseXmlDoc.Load(ResponseStream)
            
            ' Build a list of the DAV:href XML nodes, corresponding to the folders
            ' in the mailbox.  The DAV: namespace is typically assgigned the a:
            ' prefix in the XML response body.
            HrefNodes = ResponseXmlDoc.GetElementsByTagName("a:href")

            ' Build a list of the urn:schemas:httpmail:subject XML nodes,
            ' corresponding to the calendar item subjects returned in the search request.
            ' The urn:schemas:httpmail: namespace is typically
            ' assigned the e: prefix in the XML response body.
            SubjectNodeList = ResponseXmlDoc.GetElementsByTagName("e:subject")

            ' Build a list of the urn:schemas:calendar:location XML nodes,
            ' corresponding to the calendar item locations returned in the search request.
            ' The urn:schemas:calendar: namespace is typically
            ' assigned the d: prefix in the XML response body.
            LocationNodeList = ResponseXmlDoc.GetElementsByTagName("d:location")

            ' Build a list of the urn:schemas:calendar:dtstart XML nodes,
            ' corresponding to the calendar item locations returned in the search request.
            StartTimeNodeList = ResponseXmlDoc.GetElementsByTagName("d:dtstart")

            ' Build a list of the urn:schemas:calendar:dtend XML nodes,
            ' corresponding to the calendar item locations returned in the search request.
            EndTimeNodeList = ResponseXmlDoc.GetElementsByTagName("d:dtend")

            ' Build a list of the urn:schemas:calendar:busystatus XML nodes,
            ' corresponding to the calendar item locations returned in the search request.
            BusyStatusNodeList = ResponseXmlDoc.GetElementsByTagName("d:busystatus")

            ' Build a list of the urn:schemas:calendar:instancetype XML nodes,
            ' corresponding to the calendar item locations returned in the search request.
            InstanceTypeNodeList = ResponseXmlDoc.GetElementsByTagName("d:instancetype")

            ' Loop through the returned items (if any).
            If SubjectNodeList.Count > 0 Then

                Dim i As Integer
                For i = 0 To SubjectNodeList.Count - 1

                    ' Display the subject.

                    output = output & SubjectNodeList(i).InnerText & ControlChars.CrLf
                    Console.WriteLine(" " + SubjectNodeList(i).InnerText)

                    ' Display the location.
                    'Console.WriteLine("  Location:      " + LocationNodeList(i).InnerText)

                    ' Display the start time.
                    'Console.WriteLine("  Start time:    " + StartTimeNodeList(i).InnerText)

                    ' Display the end time.
                    'Console.WriteLine("  End time:      " + EndTimeNodeList(i).InnerText)

                    ' Display the busy status.
                    'Console.WriteLine("  Busy status:   " + BusyStatusNodeList(i).InnerText)

                    ' Display the instance type.
                    'If InstanceTypeNodeList(i).InnerText = "0" Then
                    '    Console.WriteLine("  Instance type: 0-Single appointment")
                    'ElseIf InstanceTypeNodeList(i).InnerText = "1" Then
                    '    Console.WriteLine("  Instance type: 1-Master recurring appointment")
                    'ElseIf InstanceTypeNodeList(i).InnerText = "2" Then
                    '    Console.WriteLine("  Instance type: 2-Single instance, recurring appointment")
                    'ElseIf InstanceTypeNodeList(i).InnerText = "3" Then
                    '    Console.WriteLine("  Instance type: 3-Exception to a recurring appointment")
                    'Else
                    '    Console.WriteLine("  Instance type: Unknown")
                    '    Console.WriteLine("")
                    'End If

                Next

            Else
                Console.WriteLine("No calendar items found ...")

            End If

            ' Clean up.
            ResponseStream.Close()
            Response.Close()

        Catch ex As Exception

            ' Catch any exceptions. Any error codes from the
            ' SEARCH method requests on the server will be caught
            ' here, also.
            Console.WriteLine(ex.Message)

        End Try

        SaveTextFile("C:\test.txt", output)
        emailCalendar()
        Me.Close()

Quick and dirty email server checker, python

// description of your code here
This sends an email from a gmail account with a GUID for the subject to another email account, and then writes this GUID to file. On the other end, the other half of the program checks the GUID in the recieved message and matches it to the GUID in the file to verify that the message has been recieved. I schedule the sender to run every ten minutes, and the reciever/checker to run every minute. The reciever has a threshold value of 20 so if it has checked 20 times and not recieved the email it sends an IM to my gmail account. Whew is that contrived or what.
// First part, email sender, schedule to run every 10 minutes or so
// this uses GUID from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163604

from smtplib import SMTP
from socket import sslerror         #if desired
import Guid
import os

guidSubj = Guid.generate()
guidBod1 = Guid.generate()
guidBod2 = Guid.generate()

if not os.path.exists("sent.txt"):   #check whether the file exists, if not create it
    fileHandle = open('sent.txt','w')
    fileHandle.write (guidSubj)
    fileHandle.close()
    server = SMTP('smtp.gmail.com',587)
    server.set_debuglevel(1) # or 1 for verbosity
    server.ehlo('user@gmail.com')
    server.starttls()
    server.ehlo('user@gmail.com')  # say hello again
    server.login('user@gmail.com', 'password')
    # i have a suspicion that smptlib does not add the required newline dot newline so i do it myself
    server.sendmail('user@gmail.com', 'user@place.com', "Subject:Ping," + guidSubj + '\n\n' + guidBod1 + '\n\n' + guidBod2 + '\n.\n')
    # next line generates the ignorable socket.sslerror
    server.quit()

// Second email checker/reciever, check every minute or so
# This script is a helper to clean POP3 mailboxes
# containing malformed mails that hangs MUA's, that 
# are too large, or whatever...
#
# It iterates over the non-retrieved mails, prints
# selected elements from the headers and prompt the 
# user to delete bogus messages.
#
# Written by Xavier Defrang <xavier.defrang@brutele.be>
# 

# 
import getpass, poplib, re, os, fileinput, sys, xmpp

def sendIM(toAddress=None):
    
    # Google Talk constants
    FROM_GMAIL_ID = "user@gmail.com"
    GMAIL_PASS = "pass"
    GTALK_SERVER = "talk.google.com"
    TO_GMAIL_ID = "user@gmail.com"
    jid=xmpp.protocol.JID(FROM_GMAIL_ID)
    cl=xmpp.Client(jid.getDomain(),debug=[])
    if not cl.connect((GTALK_SERVER,5222)):
        raise IOError('Can not connect to server.')
    if not cl.auth(jid.getNode(),GMAIL_PASS):
        raise IOError('Can not auth with server.')

    cl.send( xmpp.Message( TO_GMAIL_ID ,"Fix your email!" ) )
    cl.disconnect()

# Change this to your needs
POPHOST = "131.0.0.1"
POPUSER = "user"
POPPASS = "pass"

# How many lines of message body to retrieve
MAXLINES = 10

# Headers we're actually interrested in
rx_headers  = re.compile(r"^(Subject)")

try:

    # Connect to the POPer and identify user
    pop = poplib.POP3(POPHOST)
    pop.user(POPUSER)

    if not POPPASS:
        # If no password was supplied, ask for it
        POPPASS = getpass.getpass("Password for %s@%s:" % (POPUSER, POPHOST))

    # Authenticate user
    pop.pass_(POPPASS)

    # Get some general informations (msg_count, box_size)
    stat = pop.stat()

    bye = 0
    count_del = 0
    
    #for n in range(stat[0]):

    msgnum = stat[0]

    # Retrieve headers
    response, lines, bytes = pop.top(msgnum, MAXLINES)

    # Print message info and headers we're interrested in
    test = "".join(filter(rx_headers.match, lines))
    num = test.split(',')
    out = num[1]
    

    #Read the sent.txt file to get the GUID
    fileHandle = open ( 'sent.txt' )
    sentGuid = fileHandle.readline()
    print sentGuid
    fileHandle.close()
    
    if out == sentGuid:
        print "They match!! yay"
        pop.dele(msgnum)
        print "Message %d marked for deletion" % msgnum
        count_del += 1
        #delete the retry.txt and sent.txt file
        os.remove("retry.txt")
        os.remove("sent.txt")
    else:

        #There are no messages yet, so we will increment the retry value
        if not os.path.exists("retry.txt"):
            fileHandle = open ( 'retry.txt','a')
            fileHandle.write('1')
            fileHandle.close()
        else:
        
        fileHandle = open("retry.txt")
        retryValue = fileHandle.readline()
        fileHandle.close()
        #delete the file then recreate with new value
        os.remove('retry.txt')

        if retryValue != '':
            retryValue = int(retryValue) + 1
            out = str(retryValue)
            fileHandle = open ( 'retry.txt','a')
            fileHandle.write(out)
            fileHandle.close()
            if retryValue > 20 and retryValue <25:
                sendIM()

   # Summary
    print "Deleting %d message(s) in mailbox %s@%s" % (count_del, POPUSER, POPHOST)

    # Commit operations and disconnect from server
    print "Closing POP3 session"
    pop.quit()

except poplib.error_proto, detail:

    # Fancy error handling
    print "POP3 Protocol Error:", detail

    #There are no messages yet, so we will increment the retry value
    if not os.path.exists("retry.txt"):
        fileHandle = open ( 'retry.txt','a')
        fileHandle.write('1')
        fileHandle.close()
    else:
        
        fileHandle = open("retry.txt")
        retryValue = fileHandle.readline()
        fileHandle.close()
        #delete the file then recreate with new value
        os.remove('retry.txt')

        if retryValue != '':
            retryValue = int(retryValue) + 1
            out = str(retryValue)
            fileHandle = open ( 'retry.txt','a')
            fileHandle.write(out)
            fileHandle.close()
            if retryValue > 20 and retryValue <25:
                sendIM()

How to send IM jabber message to google chat using python and xmppy

// From http://www.franklinmint.fm/blog/archives/000603.html
// This works with version xmpppy-0.4.0.win32.exe from http://xmpppy.sourceforge.net/
import sys,xmpp

# Google Talk constants
FROM_GMAIL_ID = "user@gmail.com"
GMAIL_PASS = "password"
GTALK_SERVER = "talk.google.com"
TO_GMAIL_ID = "user@gmail.com"

jid=xmpp.protocol.JID(FROM_GMAIL_ID)
cl=xmpp.Client(jid.getDomain(),debug=[])
if not cl.connect((GTALK_SERVER,5222)):
    raise IOError('Can not connect to server.')
if not cl.auth(jid.getNode(),GMAIL_PASS):
    raise IOError('Can not auth with server.')

cl.send( xmpp.Message( "someone@gmail.com" ,"Hi" ) )
cl.disconnect()
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS