Mik K
Mik K

Reputation: 21

How can I time a wmi connection try, or check a remote host avail before connecting?

I have a script which connects to a lot of hosts through wmi like this :

wmi.WMI(ip, user=username, password=password))

However, often many of the hosts are not available and the connection tentative takes a lot of time before the script is allowed to try the next host.

I would like to be able to test the remote host for availability before trying to connect to it, or to be able to set a timeout for the connection.

Any idea?

Upvotes: 0

Views: 488

Answers (1)

Harry
Harry

Reputation: 1263

You experience a network timeout, the times for this are buried deeply in the windows registry (network stack).

There are many possible solutions for your problem, mine would be (other than using multiple threads) to introduce a custom timeout (e.g. 5 seconds instead of 75 default seconds)

Funny enough, the Windows powershell wmi object does introduce a timeout option out of the box while the python one does not. So one way to deal with your problem is to implement your own timeout. In python, one way to do it is like this:

https://pythonadventures.wordpress.com/2012/12/08/raise-a-timeout-exception-after-x-seconds/

import signal
import time

def test_request(arg=None):
    """Your http request."""
    time.sleep(2)
    return arg

class Timeout():
    """Timeout class using ALARM signal."""
    class Timeout(Exception):
        pass

    def __init__(self, sec):
        self.sec = sec

    def __enter__(self):
        signal.signal(signal.SIGALRM, self.raise_timeout)
        signal.alarm(self.sec)

    def __exit__(self, *args):
        signal.alarm(0)    # disable alarm

    def raise_timeout(self, *args):
        raise Timeout.Timeout()

def main():
    # Run block of code with timeouts
    try:
        with Timeout(3):
            print test_request("Request 1")
        with Timeout(1):
            print test_request("Request 2")
    except Timeout.Timeout:
        print "Timeout"

#############################################################################

if __name__ == "__main__":
    main()

Upvotes: 1

Related Questions