if 用户不是root ,切换为root ,通过self.ssh.invoke_shell().send(self.cmd1)发送命令
else 用户是root, 可以通过 paramiko.SSHClient().exec_command(self.cmd1)直接发送命令
代码如下:
def exc_cmd(self):
try:
# test cmd
# cmd = "cd %s;mkdir %s" % (" /home/", "test02")
print("********test if root*********")
ssh_to_root = self.ssh.invoke_shell()
if self.user != 'root':
print("********test if root begin*********")
time.sleep(0.1)
ssh_to_root.send('sudo -i')
ssh_to_root.send('\n')
buff = ''
while not buff.endswith('password: '):
resp = ssh_to_root.recv(9999)
buff += resp
ssh_to_root.send("mima123")
ssh_to_root.send('\n')
print("********send password*********")
buff = ''
while not buff.endswith('# '):
resp = ssh_to_root.recv(9999)
buff += resp
ssh_to_root.send(self.cmd1)
ssh_to_root.send('\n')
print("********send cmd1 end*********")
buff = ''
while not buff.endswith('# '):
resp = ssh_to_root.recv(9999)
buff += resp
ssh_to_root.send(self.cmd2)
ssh_to_root.send('\n')
print("********send cmd2 end*********")
else:
stdout0, stdin0, stderr0 = self.ssh.exec_command(self.cmd1)
time.sleep(3)
print(stdout0, stdin0, stderr0)
stdout1, stdin1, stderr1 = self.ssh.exec_command(self.cmd2)
time.sleep(3)
print(stdout1, stdin1, stderr1)
stdout2, stdin2, stderr2 = self.ssh.exec_command(self.cmd3)
time.sleep(3)
print(stdout2, stdin2, stderr2)
print("run shell start \n"
"*************************************************************\n")
except Exception as e:
print("exc_cmd Failed")