測試工具開發(2)pexpect.spawn

pexpect.spawn

重點:

The logfile member turns on or off logging. All input and output will
be copied to the given file object. Set logfile to None to stop
logging. This is the default. Set logfile to sys.stdout to echo
everything to standard output. The logfile is flushed after each write.

Example log input and output to a file::

    child = pexpect.spawn('some_command')
    fout = open('mylog.txt','wb')
    child.logfile = fout

Example log to stdout::

    # In Python 2:
    child = pexpect.spawn('some_command')
    child.logfile = sys.stdout

    # In Python 3, we'll use the ``encoding`` argument to decode data
    # from the subprocess and handle it as unicode:
    child = pexpect.spawn('some_command', encoding='utf-8')
    child.logfile = sys.stdout

 

#-*-coding:utf8-*-
#!/usr/bin/env python

import pexpect
import os
import traceback
import logging

loginprompt = '[$#>]'

def ssh_cli(user, host, password):
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
    log_path = os.getcwd() + '/logs/'
    filename = os.path.split(__file__)[-1].split(".")[0]
    log_name = log_path + filename + "_" + rq + '.log'
    logfile = log_name
    # 控制檯log,會打印到屏幕
    fh = logging.FileHandler(logfile, mode='w')
    # 文件log,保存到以本文件同名的log
    ch = logging.StreamHandler()

    ch.setLevel(logging.DEBUG)
    fh.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    logger.addHandler(fh)

    # ssh host log
    fout = open('./logs/cli.log', "wb")

    # 爲 ssh 命令生成一個 spawn 類的子程序對象.
    cmd = 'ssh %s@%s' % (user, host)
    child = pexpect.spawn(cmd)
    logger.debug("send cmd: %s" % cmd)
    child.logfile = fout
    i = child.expect(['password:', pexpect.TIMEOUT, pexpect.EOF])

    if i == 0:
        logger.info("等待輸入密碼...")
        child.sendline(password)
        child.expect(loginprompt)
        logger.info("ssh aliyun host successfully")
        child.sendline("uname -a")
        child.expect("uname -a")
        logger.info("uname -a 執行成功")
        child.expect(loginprompt)
        logger.info(child.before)
        logger.info("PASSED")

    # 如果登錄超時,打印出錯信息,並退出.
    if i != 0: # Timeout
        print 'ERROR!'
        print 'SSH could not login. Here is what SSH said:'
        print child.before, child.after
        return None

    fout.write('\n')
    fout.close()
    return child

def main ():
    host = "192.168.1.123"
    user = "root"
    password = "root"
    child = ssh_cli(user, host, password)
    child.close(force=True)

if __name__ == '__main__':
    try:
        main()
    except Exception, e:
        print str(e)
        traceback.print_exc()
        os._exit(1)

 

運行:

$ python test.py 
2020-06-09 22:24:12,984 - test.py[line:56] - INFO: 等待輸入密碼...
2020-06-09 22:24:13,445 - test.py[line:59] - INFO: ssh aliyun host successfully
2020-06-09 22:24:13,513 - test.py[line:62] - INFO: uname -a 執行成功
2020-06-09 22:24:13,514 - test.py[line:64] - INFO: 
Linux 4.4.0-85-generic 
2020-06-09 22:24:13,515 - test.py[line:65] - INFO: PASSED
$ 



$ cat logs/cli.log 
...
Welcome to Alibaba Cloud Elastic Compute Service !
Last login: Tue Jun  9 22:16:59 2020 from 123.118.134.33
root@localhost:~# uname -a
uname -a
Linux 4.4.0-85-generic #108~14.04.1-Ubuntu SMP Tue Jul 4 12:02:51 UTC 2017 i686 i686 i686 GNU/Linux
$ 



$ cat logs/test_202006092224.log
2020-06-09 22:24:12,984 - test.py[line:56] - INFO: 等待輸入密碼...
2020-06-09 22:24:13,445 - test.py[line:59] - INFO: ssh aliyun host successfully
2020-06-09 22:24:13,513 - test.py[line:62] - INFO: uname -a 執行成功
2020-06-09 22:24:13,514 - test.py[line:64] - INFO: 
Linux 4.4.0-85-generic 
2020-06-09 22:24:13,515 - test.py[line:65] - INFO: PASSED
$ 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章