from
ldap3
import
Server, Connection,
ALL
, SUBTREE, Tls
import
ssl
import
getpass
try
:
from
config
import
USERNAME, PASSWORD
except
ImportError:
USERNAME, PASSWORD
=
None
,
None
LDAP_SERVER
=
'ad.example.com'
LDAP_PORT
=
636
def
get_subnets_and_sites(username, password):
tls_configuration
=
Tls(validate
=
ssl.CERT_REQUIRED, version
=
ssl.PROTOCOL_TLSv1_2)
server
=
Server(LDAP_SERVER, port
=
LDAP_PORT, use_ssl
=
True
, tls
=
tls_configuration, get_info
=
ALL
)
connection
=
Connection(server, user
=
username, password
=
password, authentication
=
'SIMPLE'
, auto_bind
=
True
)
search_base
=
'CN=Subnets,CN=Sites,CN=Configuration,DC=example,DC=com'
search_filter
=
'(objectClass=subnet)'
search_attributes
=
[
'cn'
,
'siteObject'
]
connection.search(search_base, search_filter, SUBTREE, attributes
=
search_attributes)
subnets_sites
=
[]
for
entry
in
connection.entries:
subnet_name
=
entry.cn.value
site_dn
=
entry.siteObject.value
if
entry.siteObject
else
"No site assigned"
subnets_sites.append((subnet_name, site_dn))
return
subnets_sites
def
print_subnets_and_sites(subnets_sites):
if
subnets_sites:
print
(
"\nSubnets and their Site Assignments:"
)
for
subnet, site
in
subnets_sites:
print
(f
"Subnet: {subnet}, Site: {site}"
)
else
:
print
(
"No subnets found in the domain."
)
def
main():
username
=
USERNAME
if
USERNAME
else
input
(
"Enter your LDAP username: "
)
password
=
PASSWORD
if
PASSWORD
else
getpass.getpass(
"Enter your LDAP password: "
)
subnets_sites
=
get_subnets_and_sites(username, password)
print_subnets_and_sites(subnets_sites)
if
__name__
=
=
"__main__"
:
main()