python2.7 paramiko 切换root用户,远程执行脚本

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")

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值