paramiko 实现远程切换root

# 远程执行docker 命令
def exec_cod(host, username, password, port, root_pwd, image_count, cmd, cmd2):
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostname=host, port=int(port), username=username, password=password)
    if username != 'root':
        ssh = s.invoke_shell()
        time.sleep(0.1)
        ssh.send('su - \n')
        buff = ''
        while not buff.endswith('Password: '):
            resp = ssh.recv(9999)
            buff += resp.decode('utf-8')
        ssh.send(root_pwd)
        ssh.send('\n')
        buff = ''
        while not buff.endswith('# '):
            resp = ssh.recv(9999)
            buff += resp.decode('utf-8')
        if host == '10.210.0.71' or host == '10.210.0.73':
            ssh.send('docker-compose -f /home/ubuntu/ruo/docker-compose.yml scale php=' + str(image_count))
        else:
            ssh.send('docker-compose -f /root/ubuntu/ruo/docker-compose.yml scale php=' + str(image_count))
        ssh.send('\n')
        buff = ''
        while not buff.endswith('# '):
            resp = ssh.recv(9999)
            buff += resp.decode('utf-8')
        print(buff)
        if host == '10.210.0.71' or host == '10.210.0.73':
            ssh.send('docker-compose -f /home/ubuntu/ruo/docker-compose.yml restart')
        else:
            ssh.send('docker-compose -f /root/ubuntu/ruo/docker-compose.yml restart')
        ssh.send('\n')

        buff = ''
        while not buff.endswith('# '):
            resp = ssh.recv(9999)
            buff += resp.decode('utf-8')
        print(buff)
        ssh.send('docker ps')
        ssh.send('\n')
        buff = ''
        while not buff.endswith('# '):
            resp = ssh.recv(9999)
            buff += resp.decode('utf-8')
        s.close()
        result = buff
        print(buff)
    else:
        pass
        # stdin, stdout, stderr = s.exec_command(cmd)
        # result = stdout.read()
        # s.close()
    return result

  

posted @ 2018-05-27 15:02  qukaige  阅读(1748)  评论(0编辑  收藏  举报