支持预安装结束选择是否删除root互信

支持预安装建立root互信不影响老的互信关系
日志记录行号,方便定位
This commit is contained in:
hangjin2020
2022-04-29 16:07:27 +08:00
parent 4ec444dff8
commit 1f6d7f369d
7 changed files with 70 additions and 33 deletions

View File

@ -69,6 +69,7 @@ class Preinstall(ParallelBaseOM):
self.is_new_root_path = False
self.ips = ""
self.root_ssh_agent_flag = False
self.root_delete_flag = False
self.user_ssh_agent_flag = False
def usage(self):
@ -157,6 +158,9 @@ General options:
# parameter --non-interactive
if (ParaDict.__contains__("preMode")):
self.preMode = ParaDict.get("preMode")
# parameter --delete-root-trust
if (ParaDict.__contains__("root_delete_flag")):
self.root_delete_flag = ParaDict.get("root_delete_flag")
def checkUserParameter(self):
"""

View File

@ -146,10 +146,10 @@ class GaussCreateTrust():
self.failedToAppendInfo = ""
self.homeDir = os.path.expanduser("~" + self.user)
self.sshDir = "%s/.ssh" % self.homeDir
self.authorized_keys_fname = '%s/.ssh/authorized_keys' % self.homeDir
self.known_hosts_fname = '%s/.ssh/known_hosts' % self.homeDir
self.id_rsa_fname = '%s/.ssh/id_rsa' % self.homeDir
self.id_rsa_pub_fname = self.id_rsa_fname + '.pub'
self.authorized_keys_fname = DefaultValue.SSH_AUTHORIZED_KEYS
self.known_hosts_fname = DefaultValue.SSH_KNOWN_HOSTS
self.id_rsa_fname = DefaultValue.SSH_PRIVATE_KEY
self.id_rsa_pub_fname = DefaultValue.SSH_PUBLIC_KEY
self.skipHostnameSet = False
self.isKeyboardPassword = False
# init SshTool
@ -712,9 +712,9 @@ General options:
self.logger.log("Creating the local key file.", "addStep")
else:
self.logger.log("Creating the local key file.")
if os.path.exists(self.sshDir):
FileUtil.removeDirectory(self.sshDir)
FileUtil.removeFile(self.id_rsa_fname)
FileUtil.removeFile(self.id_rsa_pub_fname)
secret_word = self.get_secret(32)
self.secret_word = secret_word
localDirPath = os.path.dirname(os.path.realpath(__file__))
@ -768,10 +768,10 @@ General options:
FileUtil.createFileInSafeMode(self.authorized_keys_fname)
f = open(self.authorized_keys_fname, 'a+')
for line in f:
if line.strip() == self.localID:
if line.strip() == self.localID + " #OM":
# The localID is already in authorizedKeys; no need to add
return
f.write(self.localID)
f.write(self.localID + " #OM")
f.write('\n')
self._log("Successfully appended local ID to authorized_keys.", "constant")
finally:
@ -808,6 +808,7 @@ General options:
hostnameList.append(value)
for hostname in hostnameList:
cmd = 'ssh-keyscan -t ed25519 %s >> %s ' % (hostname, self.known_hosts_fname)
cmd += '&& sed -i "$ s/$/ #OM/" %s ' % self.known_hosts_fname
cmd += "&& chmod %s %s" % (DefaultValue.KEY_FILE_MODE, self.known_hosts_fname)
(status, output) = subprocess.getstatusoutput(cmd)
if status != 0:
@ -896,14 +897,14 @@ General options:
# Append the ID to authorized_keys;
cnt = 0
cmd = 'echo \"%s\" >> .ssh/authorized_keys && echo ok ok ok' % self.localID
cmd = 'echo \"%s #OM\" >> .ssh/authorized_keys && echo ok ok ok' % self.localID
(cin, cout, cerr) = p.exec_command(cmd)
cin.close()
#readline will read other msg.
line = cout.read().decode()
while line.find("ok ok ok") < 0:
time.sleep(cnt * 2)
cmd = 'echo \"%s\" >> .ssh/authorized_keys && echo ok ok ok' % self.localID
cmd = 'echo \"%s #OM\" >> .ssh/authorized_keys && echo ok ok ok' % self.localID
(cin, cout, cerr) = p.exec_command(cmd)
cin.close()
cnt += 1
@ -964,11 +965,13 @@ General options:
input : tab, line
output: True/False
"""
IDKey = line.strip().split()
if not (len(IDKey) == 3 and line[0] != '#'):
return False
tab[IDKey[2]] = line
return True
key = line.strip().split()
if line[0] == "#":
return True
elif len(key) != 4:
tab[line] = line
else:
tab[key[2] + key[3]] = line
def readAuthorizedKeys(self, tab=None, keysFile=None):
"""
@ -1004,10 +1007,12 @@ General options:
output: True/False
"""
key = line.strip().split()
if not (len(key) == 3 and line[0] != '#'):
return False
tab[key[0]] = line
return True
if line[0] == "#":
return True
elif len(key) != 4:
tab[line] = line
else:
tab[key[0] + key[3]] = line
def readKnownHosts(self, tab=None, hostsFile=None):
"""
@ -1045,8 +1050,15 @@ General options:
bashrc_file = os.path.join(pwd.getpwuid(os.getuid()).pw_dir, ".bashrc")
cmd = 'source %s;' %bashrc_file
cmd += ('scp -q -o "BatchMode yes" -o "NumberOfPasswordPrompts 0" ' +
'%s %s %s %s %s:.ssh/' % (self.authorized_keys_fname, self.known_hosts_fname,
self.id_rsa_fname, self.id_rsa_pub_fname, hostname))
'%s %s %s:.ssh/' % (self.id_rsa_fname, self.id_rsa_pub_fname, hostname))
cmd += ''' && temp_auth=$(grep '#OM' %s)''' \
''' && ssh %s "sed -i '/#OM/d' %s; echo '${temp_auth}' >> %s"''' % (
self.authorized_keys_fname, hostname, self.authorized_keys_fname,
self.authorized_keys_fname)
cmd += ''' && temp_auth=$(grep '#OM' %s)''' \
''' && ssh %s "sed -i '/#OM/d' %s; echo '${temp_auth}' >> %s"''' % (
self.known_hosts_fname, hostname, self.known_hosts_fname,
self.known_hosts_fname)
(status, output) = subprocess.getstatusoutput(cmd)
if status != 0:
raise Exception(ErrorCode.GAUSS_502["GAUSS_50223"] %"the authentication"

View File

@ -485,6 +485,11 @@ class DefaultValue():
# Cert type
GRPC_CA = "grpc"
SERVER_CA = "server"
# rsa file name
SSH_PRIVATE_KEY = os.path.expanduser("~/.ssh/id_om")
SSH_PUBLIC_KEY = os.path.expanduser("~/.ssh/id_om.pub")
SSH_AUTHORIZED_KEYS = os.path.expanduser("~/.ssh/authorized_keys")
SSH_KNOWN_HOSTS = os.path.expanduser("~/.ssh/known_hosts")
@staticmethod
def encodeParaline(cmd, keyword):
@ -2524,7 +2529,7 @@ class DefaultValue():
:return:
"""
DefaultValue.clear_ssh_id_rsa(mpprcfile, logger)
id_rsa_path = os.path.expanduser("~/.ssh/id_rsa")
id_rsa_path = DefaultValue.SSH_PRIVATE_KEY
cmd = "source %s;echo \"%s\" | /bin/sh %s %s" %(
mpprcfile, str(secret_word), shell_file, id_rsa_path)
if logger:
@ -2704,7 +2709,7 @@ class DefaultValue():
if logger:
logger.debug("Successfully to clear id_rsa in ssh-agent")
id_rsa_path = os.path.expanduser("~/.ssh/id_rsa")
id_rsa_path = DefaultValue.SSH_PRIVATE_KEY
cmd = "source %s;echo \"%s\" | /bin/sh %s %s" % (
mpprcfile, str(secret_word), shell_file, id_rsa_path)
if logger:

View File

@ -378,6 +378,12 @@ class GaussLog:
self.step = self.step + 1
return self.step
@staticmethod
def get_log_file_line():
f = sys._getframe().f_back.f_back.f_back
return "%s(%s:%s)" % (os.path.basename(f.f_code.co_filename), f.f_code.co_name,
str(f.f_lineno))
def __writeLog(self, level, msg, stepFlag=""):
"""
function: Write log to file
@ -411,14 +417,15 @@ class GaussLog:
msg = replace_reg.sub('-A *** ', str(msg))
strTime = datetime.datetime.now()
file_line = self.get_log_file_line()
if (stepFlag == ""):
print("[%s][%d][%s][%s]:%s" % (
strTime, self.pid, self.moduleName, level, msg),
print("[%s][%d][%s][%s][%s]:%s" % (
strTime, self.pid, file_line, self.moduleName, level, msg),
file=self.fp)
else:
stepnum = self.Step(stepFlag)
print("[%s][%d][%s][%s][Step%d]:%s" % (
strTime, self.pid, self.moduleName, level, stepnum, msg),
print("[%s][%d][%s][%s][%s][Step%d]:%s" % (
strTime, self.pid, file_line, self.moduleName, level, stepnum, msg),
file=self.fp)
self.fp.flush()
self.lock.release()

View File

@ -65,7 +65,7 @@ VALUE_CHECK_LIST = ["|", ";", "&", "$", "<", ">", "`", "\\", "'", "\"", "{",
gs_preinstall = ["-?", "--help", "-V", "--version", "-U:", "-G:", "-L",
"--skip-os-set", "-X:",
"--env-var=", "--sep-env-file=", "--skip-hostname-set",
"-l:", "--non-interactive"]
"-l:", "--non-interactive", "--delete-root-trust"]
gs_install = ["-?", "--help", "-V", "--version", "-X:", "-l:",
"--gsinit-parameter=", "--dn-guc=", "--cms-guc=",
"--time-out=", "--alarm-component="]
@ -374,7 +374,8 @@ class Parameter():
"--krb-server": "krb-server",
"--krb-client": "krb-client",
"--non-print": "nonPrinting",
"--dynamic": "dynamic"
"--dynamic": "dynamic",
"--delete-root-trust": "root_delete_flag"
}
parameterIsBool_keys = parameterIsBool.keys()

View File

@ -233,13 +233,18 @@ class PreinstallImpl:
return
if self.context.preMode or not self.context.root_ssh_agent_flag:
return
if not self.context.root_delete_flag:
return
self.context.logger.debug("Start Delete root mutual trust")
# get dir path
username = pwd.getpwuid(os.getuid()).pw_name
homeDir = os.path.expanduser("~" + username)
sshDir = "%s/.ssh/*" % homeDir
tmp_path = "%s/gaussdb_tmp" % homeDir
authorized_keys = DefaultValue.SSH_AUTHORIZED_KEYS
known_hosts = DefaultValue.SSH_KNOWN_HOSTS
ssh_private = DefaultValue.SSH_PRIVATE_KEY
ssh_pub = DefaultValue.SSH_PUBLIC_KEY
# get cmd
bashrc_file = os.path.join(pwd.getpwuid(os.getuid()).pw_dir, ".bashrc")
@ -247,7 +252,10 @@ class PreinstallImpl:
"xargs kill -9"
delete_line_cmd = " ; sed -i '/^\\s*export\\s*SSH_AUTH_SOCK=.*$/d' %s" % bashrc_file
delete_line_cmd += " && sed -i '/^\\s*export\\s*SSH_AGENT_PID=.*$/d' %s" % bashrc_file
delete_shell_cmd = " && rm -rf %s && rm -rf %s" % (sshDir, tmp_path)
delete_shell_cmd = " && rm -rf %s" % tmp_path
delete_shell_cmd += " && rm -f %s && rm -f %s" % (ssh_private, ssh_pub)
delete_shell_cmd += " && sed -i '/#OM/d' %s " % authorized_keys
delete_shell_cmd += " && sed -i '/#OM/d' %s " % known_hosts
cmd = "%s" + delete_line_cmd + delete_shell_cmd
# get remote node and local node

View File

@ -14,7 +14,7 @@ cmd2="$3"
func_sshkeygen_cmd()
{
cmd="ssh-keygen -t ed25519 -N \"$passwd\" -f ~/.ssh/id_rsa < /dev/null && chmod 600 ${cmd1} ${cmd2}"
cmd="ssh-keygen -t ed25519 -N \"$passwd\" -f ~/.ssh/id_om < /dev/null && chmod 600 ${cmd1} ${cmd2}"
eval $cmd
}