登陆远程虚机,切换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()