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

  

转载于:https://www.cnblogs.com/412013cl/p/9096122.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值