python之paramiko实践

登陆远程虚机,切换root账户,登陆docker 容器,执行命令

import paramiko, re, time

VM_LIST = ['2020:138:ab05:138:0:0:0:208', '193.92.0.45']
username = 'admin'
password = '123'
#password = '123456'
root_password = '123456'
port_remote = 22

def printLog(logFile, logContents):
    print(logContents)
    print(logContents, file=logFile)

def execSshCmd(chanObj, logFile, cmd, endMark, keyFlag):
    printLog(logFile, "---------- execSshCmd start ----------")
    # printLog("cmd : %s, endMark : %s, keyFlag : %s" % (cmd, endMark, keyFlag))
    try:
        if keyFlag == True:
            chanObj.send(cmd)
            chanObj.send('\n')
            chanObj.send('\n')
            output = ''
            # while not chanObj.recv_ready():
                # time.sleep(0.02)
            while not endMark in output:
                time.sleep(0.3)
                resp = chanObj.recv(9999).decode()
                output += resp
                printLog(logFile, output.strip())
        else:
            chanObj.send(cmd)
            chanObj.send('\n')
            chanObj.send('\n')
            # while not chanObj.recv_ready():
                # time.sleep(0.02)
            time.sleep(0.3)
            output = chanObj.recv(9999).decode()
            printLog(logFile, output.strip())
    except Exception as e:
        printLog(logFile, "execSshCmd deal failed, cmd:" + cmd + ", error cause:" + str(e) +" !!!")
    finally:
        printLog(logFile, "---------- execSshCmd end   ----------")

def loginVmAutoExecCmd(ip_remote, port_remote, username, password, root_password, logFile):
    printLog(logFile, "======================================")
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(ip_remote,port_remote,username=username,password=password,timeout=5) #  timeout
        printLog(logFile, "Successfully login vm %s, username:%s, time:%s" % (ip_remote, username, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())))
        stdin, stdout, stderr = ssh.exec_command("pwd")
        printLog(logFile, stdout.readlines())

        chan = ssh.invoke_shell()
        time.sleep(0.1)
        execSshCmd(chan, logFile, "su",          'Password: ', True)
        execSshCmd(chan, logFile, root_password, '# ',         True)
        execSshCmd(chan, logFile, "whoami",      '# ',         True)
        execSshCmd(chan, logFile, "docker ps",   '# ',         True)

        cmd = r"docker attach $(docker ps | grep kafka | awk '{print $1}')"
        execSshCmd(chan, logFile, cmd,           '# ',         True)

        for idx in range(4, 10):         # 4 ~ 9
            cmd = "sh " + str(idx)
            execSshCmd(chan, logFile, cmd,       '# ',         True)

    except Exception as e:
        printLog(logFile, "==============")
        printLog(logFile, "VM deal failed, ip:" + ip_remote + ", error cause:" + str(e) + " !!!")
    finally:
        printLog(logFile, "======================================")
        printLog(logFile, "VM finished, ip:" + ip_remote + ", SSH CLOSED")
        ssh.close()

if __name__ == '__main__':

    logFile = open(re.sub("\s", "_", ("autoExec_" + str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) + ".log")),'w',encoding='utf_8_sig')

    for vm_ip in VM_LIST:
        printLog(logFile, "=======================================================================================")
        loginVmAutoExecCmd(vm_ip, port_remote, username, password, root_password, logFile)
        printLog(logFile, "=======================================================================================")

    logFile.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值