samba-tool: add a function to cleanly demote a DC
[Samba/gebeck_regimport.git] / source4 / scripting / python / samba / netcmd / common.py
blob9291f872aba196ad3fb95549271e2623217dc3dd
1 #!/usr/bin/env python
3 # common functions for samba-tool python commands
5 # Copyright Andrew Tridgell 2010
6 # Copyright Giampaolo Lauria 2011 <lauria2@yahoo.com>
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 import re
23 from samba.dcerpc import nbt
24 from samba.net import Net
27 def _get_user_realm_domain(user):
28 """ get the realm or the domain and the base user
29 from user like:
30 * username
31 * DOMAIN\username
32 * username@REALM
33 """
34 baseuser = user
35 realm = ""
36 domain = ""
37 m = re.match(r"(\w+)\\(\w+$)", user)
38 if m:
39 domain = m.group(1)
40 baseuser = m.group(2)
41 return (baseuser.lower(), domain.upper(), realm)
42 m = re.match(r"(\w+)@(\w+)", user)
43 if m:
44 baseuser = m.group(1)
45 realm = m.group(2)
46 return (baseuser.lower(), domain, realm.upper())
49 def netcmd_dnsname(lp):
50 '''return the full DNS name of our own host. Used as a default
51 for hostname when running status queries'''
52 return lp.get('netbios name').lower() + "." + lp.get('realm').lower()
55 def netcmd_finddc(lp, creds, realm=None):
56 '''Return domain-name of a writable/ldap-capable DC for the default
57 domain (parameter "realm" in smb.conf) unless another realm has been
58 specified as argument'''
59 net = Net(creds=creds, lp=lp)
60 if realm is None:
61 realm = lp.get('realm')
62 cldap_ret = net.finddc(domain=realm,
63 flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
64 return cldap_ret.pdc_dns_name
67 def netcmd_get_domain_infos_via_cldap(lp, creds, address=None):
68 '''Return domain informations (CLDAP record) of the ldap-capable
69 DC with the specified address'''
70 net = Net(creds=creds, lp=lp)
71 cldap_ret = net.finddc(address=address,
72 flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS)
73 return cldap_ret