python pexpect 使用笔记

处理一些批量调整配置的事,然而设备特殊无法用ansible,单个串行的登陆配置又觉得比较麻烦,于是搬了点网上找到的pexpect样例,结合当前的设备情况组装成了使用的脚本,未加异常处理等等,只是简单能用、用完结束做其它事去 :sweat_smile: 。简单整理记录如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# README:
# THIS IS FOR ××× Parameters Settings
#
# ENV: python2.7.14: 
#
# Main  --> ConnectToServerExec
#
# Execute After List ServerInfos and Fill Custom Commands.
#

import sys
import time
import pexpect

# This is the list of ××× Server Infomation
# 
ServerInfos = [

# ××× IP address, UserName, Password.

# xxx
['192.168.0.31', 'administrator', '00000000'],
['192.168.0.32', 'administrator', '111111111'],
['192.168.0.33', 'administrator', '22222222'],
['192.168.0.34', 'administrator', '33333333'],
['192.168.0.35', 'administrator', '44444444'],
# ... Other ip\usernm\pwd etc...
]

# This is the list of xxxx Commands.
# 
ServerCommands = [
# Command line.
'cd /dev/path/', 
'command2exec', 

'exit'
]


# Connect to Server and Execute commands.
def ConnectToServerExec():
    for aServer in ServerInfos:
        sshconstr = 'ssh   -o StrictHostKeyChecking=no ' + aServer[1] + '@' + aServer[0] + '  '
        print("-- "+ sshconstr)
        print(" ")
        print(" ")
        
        sshcon = pexpect.spawn(sshconstr)
        sshcon.logfile = sys.stdout
        # [email protected]'s password: 
        sshcon.expect('password:')
        sshcon.sendline(aServer[2])
        
        for aCommand in ServerCommands:
            # 命令行提示符是 />DEV-> 
            sshcon.expect('>DEV->')
            sshcon.sendline(aCommand)
        
    return 0

# Main     
if __name__ == '__main__':
    print(" ")
    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    print("-- Set xxx Info  ----BEGIN ")
    print(" ")
    
    ConnectToServerIExec()
    
    print(" ")
    print("-- Set xxx Info  ----END ")
    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    print(" ")

相对于shell的expect处理区别不大,只是IDE用起来舒服一点 :roll_eyes:

1 个赞

服务器资源由ZeptoVM赞助

Partners Wiki Discord