d76355771c89ad84527460873da6be55d8ae36c7
[tests.git] / system / PlcapiUrlScanner.py
1 #!/usr/bin/env python
2 #
3 # this checks various forms of URLS for reaching a PLCAPI
4 # i.e. with http:// or https:// (only the latter is expected to work)
5 # with or without a trailing slash
6 # using a hostname or an IP
7
8 import socket
9 import xmlrpclib
10 import traceback
11
12 class PlcapiUrlScanner:
13
14     # turns out the config has an ip but no name..
15     def __init__ (self, auth, hostname=None, ip=None, verbose=False):
16         self.auth=auth
17         if not hostname and not ip:
18             raise Exception,"PlcapiUrlScanner needs _some_ input"
19         if hostname:
20             if not ip: 
21                 try:    ip=socket.gethostbyname(hostname)
22                 except: 
23                     hostname="%s.pl.sophia.inria.fr"%hostname
24                     ip=socket.gethostbyname(hostname)
25         else:
26             if not hostname: hostname=socket.gethostbyaddr(ip)[0]
27         self.hostname=hostname
28         self.ip=ip
29         self.verbose=verbose
30         
31     def try_url (self,url):
32         try:
33             xmlrpclib.ServerProxy (url, verbose=self.verbose, allow_none=True).GetNodes(self.auth)
34             print 'YES',url
35             return True
36         except xmlrpclib.ProtocolError as e:
37             print '... (http error %s)'%e.errcode,url
38             return False
39         except Exception as e:
40             print '---',type(e).__name__,url
41             if self.verbose: traceback.print_exc()
42             return False
43
44     def try_url_expected (self, url, expected):
45         return self.try_url(url)==expected
46
47     def scan(self):
48         overall=True
49         for protocol in ['http','https']:
50             expected= protocol=='https'
51             for dest in [ self.hostname, self.ip ]:
52                 for port in [ '',':80',':443']:
53                     for path in ['PLCAPI','PLCAPI/']:
54                         if protocol=='http' and port==':443': continue
55                         if protocol=='https' and port==':80': continue
56                         url="%s://%s%s/%s"%(protocol,dest,port,path)
57                         if not self.try_url_expected (url,expected): overall=False
58         return overall
59
60 from optparse import OptionParser
61 import sys
62
63 auth={'AuthMethod':'password','Username':'root@test.onelab.eu','AuthString':'test++'}
64
65 def main ():
66     usage="%prog hostname"
67     parser=OptionParser()
68     parser.add_option("-v","--verbose",dest='verbose',action='store_true',default=False)
69     (options,args)=parser.parse_args()
70     if len(args)!=1:
71         parser.print_help()
72         sys.exit(1)
73     hostname=args[0]
74     success=PlcapiUrlScanner (auth=auth, hostname=hostname,verbose=options.verbose).scan()
75     sys.exit(0 if success else -1)
76
77 if __name__ == '__main__':
78     main()