最近由于测试CU分离,涉及到多个虚机环境的文件的拷贝、程序脚本的执行,所以写了如下python脚本来自动化执行;
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys, time, getopt
import pexpect
import commands
import shlex
import subprocess
import datetime
import socket
import io
DEBUG_FLAG = True
######################################################################
# return value
# 0 login and setup success
# -2 login failture
# -3 setup failture
######################################################################
LOGIN_FAILTURE = -2
RUN_CMD_TIMEOUT = -3
RUN_CMD_SUCCESS = 0
def ssh_remote_exec_cmd(address, user, password, cmd_list):
ret = RUN_CMD_SUCCESS
cmd_prompt = '\[?%s@.+\]?#' % user
local_cmd = 'ssh %s@%s' % (user, address)
if DEBUG_FLAG:
print '[%s] %s' % (local_cmd, cmd_list)
ssh = pexpect.spawn(local_cmd)
ssh.logfile_read = sys.stdout
expect = ssh.expect(['(?i)password:', '(?i)continue connecting (yes/no)?', cmd_prompt, pexpect.EOF, pexpect.TIMEOUT], timeout = 20)
if DEBUG_FLAG:
print 'ssh expect is %d' % expect
# Login
while True:
# ssh mutual trust mode, not need password
if 2 == expect:
break
# expect '(?i)continue connecting (yes/no)?'
elif 1 == expect:
ssh.sendline('yes')
expect = ssh.expect(['(?i)password:', pexpect.EOF, pexpect.TIMEOUT], timeout = 20)
if 0 == expect:
ssh.sendline(password)
expect = ssh.expect([cmd_prompt, '(?i)Permission denied', pexpect.EOF, pexpect.TIMEOUT], timeout = 20)
if DEBUG_FLAG:
print 'login expect is ' + str(expect)
if expect != 0:
ret = LOGIN_FAILTURE # login failture
print 'Can\'t ssh to %s ! ' % address
break
# Login success, run ssh command
if RUN_CMD_SUCCESS == ret:
for cmd in cmd_list:
# Ignore blank lines
while (ssh.expect([cmd_prompt, pexpect.EOF, pexpect.TIMEOUT], timeout = 1) == 0):
pass
ssh.sendline('%s' % cmd)
expect = ssh.expect([cmd_prompt, pexpect.EOF, pexpect.TIMEOUT], timeout = 180)
if 2 == e