4 # Copyright (C) Matthieu Patou <mat@matws.net> 2011
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 # Allow to run from s4 source directory (without installing samba)
23 sys.path.insert(0, "bin/python")
27 import samba.getopt as options
30 from samba.credentials import DONT_USE_KERBEROS
31 from samba.auth import system_session
32 from samba import param
33 from samba.provision import find_provision_key_parameters, secretsdb_self_join
34 from samba.upgradehelpers import get_ldbs, get_paths
37 __docformat__ = "restructuredText"
39 parser = optparse.OptionParser("renamedc [options]")
40 sambaopts = options.SambaOptions(parser)
41 parser.add_option_group(sambaopts)
42 parser.add_option_group(options.VersionOptions(parser))
43 credopts = options.CredentialsOptions(parser)
44 parser.add_option_group(credopts)
45 parser.add_option("--oldname",
47 parser.add_option("--newname",
50 opts = parser.parse_args()[0]
52 if len(sys.argv) == 1:
53 opts.interactive = True
54 lp = sambaopts.get_loadparm()
55 smbconf = lp.configfile
57 creds = credopts.get_credentials(lp)
58 creds.set_kerberos_state(DONT_USE_KERBEROS)
61 if __name__ == '__main__':
63 # 1) First get files paths
64 paths = get_paths(param, smbconf=smbconf)
65 # Get ldbs with the system session, it is needed for searching
66 # provision parameters
67 session = system_session()
69 ldbs = get_ldbs(paths, creds, session, lp)
70 ldbs.sam.transaction_start()
71 ldbs.secrets.transaction_start()
73 if opts.oldname is None or opts.newname is None:
74 raise Exception("Option oldname or newname is missing")
75 res = ldbs.sam.search(expression="(&(name=%s)(serverReferenceBL=*))" % opts.oldname)
77 raise Exception("Wrong number of result returned (%d), are you sure of the old name %s" %
78 (len(res), opts.oldname))
80 # Ok got it then check that the new name is not used as well
81 res2 = ldbs.sam.search(expression="(&(name=%s)(objectclass=computer))" % opts.newname)
83 raise Exception("Seems that %s is a name that already exists, pick another one" %
86 names = find_provision_key_parameters(ldbs.sam, ldbs.secrets, ldbs.idmap,
89 # First rename the entry
90 # provision put the name in upper case so let's do it too !
91 newdn = ldb.Dn(ldbs.sam, str(res[0].dn))
92 newdn.set_component(0, "cn", opts.newname.upper())
93 ldbs.sam.rename(res[0].dn, newdn)
95 # Then change password and samaccountname and dnshostname
96 msg = ldb.Message(newdn)
97 machinepass = samba.generate_random_machine_password(120, 120)
98 mputf16 = machinepass.encode('utf-16-le')
100 account = "%s$" % opts.newname.upper()
101 msg["clearTextPassword"] = ldb.MessageElement(mputf16,
102 ldb.FLAG_MOD_REPLACE,
105 msg["sAMAccountName"] = ldb.MessageElement(account,
106 ldb.FLAG_MOD_REPLACE,
109 msg["dNSHostName"] = ldb.MessageElement("%s.%s" % (opts.newname,
111 ldb.FLAG_MOD_REPLACE,
115 # Do a self join one more time to resync the secrets file
116 res = ldbs.sam.search(base=newdn, scope=ldb.SCOPE_BASE,
117 attrs=["msDs-keyVersionNumber", "serverReferenceBL"])
118 assert(len(res) == 1)
119 kvno = int(str(res[0]["msDs-keyVersionNumber"]))
120 serverbldn = ldb.Dn(ldbs.sam, str(res[0]["serverReferenceBL"]))
122 secrets_msg = ldbs.secrets.search(expression="sAMAccountName=%s$" %
123 opts.oldname.upper(),
124 attrs=["secureChannelType"])
126 secChanType = int(secrets_msg[0]["secureChannelType"][0])
128 secretsdb_self_join(ldbs.secrets, domain=names.domain,
130 domainsid=names.domainsid,
131 dnsdomain=names.dnsdomain,
132 netbiosname=opts.newname.upper(),
133 machinepass=machinepass,
134 key_version_number=kvno,
135 secure_channel_type=secChanType)
137 # Update RID set reference so we don't have to runtime fixup until the next dbcheck as there is no back link.
139 res = ldbs.sam.search(expression="(objectClass=rIDSet)", base=newdn, scope=ldb.SCOPE_ONELEVEL, attrs=[])
140 assert(len(res) == 1)
141 newridset = str(res[0].dn)
142 msg = ldb.Message(newdn)
144 msg["rIDSetReferences"] = ldb.MessageElement(newridset,
145 ldb.FLAG_MOD_REPLACE,
149 # Update the server's sites configuration
150 newserverrefdn = ldb.Dn(ldbs.sam, str(serverbldn))
151 newserverrefdn.set_component(0, "cn", opts.newname.upper())
153 ldbs.sam.rename(serverbldn, newserverrefdn)
155 msg = ldb.Message(newserverrefdn)
156 msg["dNSHostName"] = ldb.MessageElement("%s.%s" % (opts.newname,
158 ldb.FLAG_MOD_REPLACE,
163 ldbs.sam.transaction_prepare_commit()
164 ldbs.secrets.transaction_prepare_commit()
167 ldbs.secrets.rollback()
171 ldbs.sam.transaction_commit()
172 ldbs.secrets.transaction_commit()
175 ldbs.secrets.rollback()
179 #print lp.get("private dir")
180 cf = open(lp.configfile)
181 ncfname = "%s.new" % lp.configfile
182 newconf = open(ncfname, 'w')
183 for l in cf.readlines():
184 if l.find("netbios name") > 0:
185 newconf.write("\tnetbios name = %s\n" % opts.newname.upper())
190 os.rename(ncfname, lp.configfile)