当前位置: 首页 > Python > 正文

python pexpect

http://fivezh.github.io/

https://pypi.python.org/pypi/pexpect/

https://pypi.python.org/pypi/ptyprocess

http://fivezh.github.io/2016/02/15/Python-ssh-switches-control/

http://fivezh.github.io/2016/03/08/Firewall-connections-check-failure/

https://www.cnblogs.com/tobecrazy/p/3888575.html

python跟H3C 5024E交换机交互获取交换机的配置信息

Python实现快速多线程ping的方法

http://www.iplaypy.com/code/scripts-shell/ss2476.html

使用python管理Cisco设备-乾颐堂

http://blog.sina.com.cn/s/blog_6bcda55c0102xpjg.html

http://blog.chinaunix.net/uid-25149914-id-3296327.html

使用python-pexpect登录linux系统并发送命令
https://www.ibm.com/developerworks/cn/linux/l-cn-pexpect2/

http://www.pythonexample.com/code/python-pexpect-ssh-cisco/

 
#!/usr/bin/python
# -*- coding: utf-8 -*-
# filename: pexpect_test.py

import pexpect,time,sys
def sendCommt():
    demo = open("result.txt", "ab")
    demo.write('==========Log Tile: demo==========\n')
    print user
    child = pexpect.spawn('ssh %s@%s' % (user,ip))
    while True:
        i = child.expect(patterns)
        if i == CONTINUES:
            child.sendline(flag)
        elif i == PASSWD:
            child.sendline(passwd)
        elif i == OPFLAG:
            break
    for cmd in cmds:
        time.sleep(2)
        p = pexpect.spawn(cmd)
        p.logfile = demo
        p.write('=====================\n')
        p.expect(pexpect.EOF)
        print cmd
    demo.close()
    child.close()

if __name__ == '__main__':
    user = 'demo'
    ip = 'x.x.x.x'
    passwd = '1'
    cmds = ['ps','ls','pwd','ifconfig','date']
    patterns = ['Are you sure you want to continue connecting (yes/no)?','[Pp]assword:','#']
    CONTINUES,PASSWD,OPFLAG = range(len(patterns))
    flag = 'yes'
    group = '1'
    try:
        sendCommt()
    except pexpect.TIMEOUT:  
        print "TIMEOUT" 
    except pexpect.EOF:
        print "EOF"


python的PEXPECT模块进行交换机配置文件的自动备份

#!/usr/bin/python  
import sys  
import time  
import os  
import pexpect  
now = time.strftime("%y%m%d", time.localtime())     #取得系统日期  
os.mkdir("/var/ftp/%s" % now, 0777) #创建目录  
os.chmod("/var/ftp/%s" % now, 0777)  #更改目录权限  
aa = open ('/var/ftp/%s/log.txt' % now, "w") #开启日志  
fout = open ('log.txt', "w")  
IP = open('1','r') #IP地址存放的文件  
PASS = open('2','r') #PASSWORD存放的文件  
while 1:  
      READIP = IP.readline() #读取IP第一行  
      READPASS = PASS.readline() #读取PASSWORD第一行  
      if not READIP: #如果读完IPFILE最后一行,就跳出循环  
            print 'END'  
            break  
      path = now + '/' + READIP  
      foo = pexpect.spawn('telnet %s' % READIP) 创建连接  
      foo.log_file = fout  
      foo.expect(['Username:']) #等待字符串'Username:'  
      foo.sendline('admin') #输出admin  
      foo.expect(['Password:'])  
      foo.sendline('admin')  
      foo.sendline('en')  
      foo.expect(['Password:'])  
      foo.sendline(READPASS) #输出PASSWORD  
      foo.expect(['#'])  
      foo.sendline('copy flash:config.text ftp:') #通过FTP备份配置文件  
      foo.expect(['Address or name of remote host'])  
      foo.sendline('192.168.52.3') #FTP SERVER  
      foo.expect(['config.text'])  
      foo.sendline(path) #FTP上传名  
      a = foo.expect (['bytes/sec', 'Error', pexpect.EOF, pexpect.TIMEOUT)  
      if a == 0:  
            aa.write('%s......ok\n' % READIP)  
            foo.expect(['#'])  
            foo.sendline('quit')  
      if a == 1:  
            aa.write('%s......failed\n' % READIP)  
            foo.sendline('quit')  
      foo.expect(['closed'])  
      foo.interact  
#      if not READIP:   #(移动此3行至16行)  
#            print 'END'  #(移动此3行至16行)  
#            break          #(移动此3行至16行)  
print 'done'  

—-
Python读取交换机配置

import pexpect

try:

    for host in open('HK5700IPs.txt','r').readlines():
        print(host)
        #switchIP = host.strip('\\n')
        switchIP = host
        telnet = 'telnet ' + switchIP
        switchPassword = "password"
        switchEnable = 'screen-length 0 temporary'
        commandTorun = 'display current-configuration interface'
#Login to the switch
        t = pexpect.spawn(telnet)
        t.expect('Password:')
        # t.sendline('sup')
        # t.expect('word:')
        t.sendline(switchPassword)
        t.expect('>')
        t.sendline(switchEnable)
        t.expect('>')

    #Send the command
        t.sendline(commandTorun)
        t.expect('return')
        data =  t.before.decode('utf-8')   #最重要的一点,不能直接转为str必须用转码的方式

    #Closing the Telnet Connection
        t.sendline('quit')
    #t.expect('>')
    #t.sendline('quit')
        t.expect(pexpect.EOF)

    #Opening the file and writing the data to it
        f = open('Temp.txt','w')
        f.write(data)
        f.close()
        new_configure = open(switchIP.strip('\n') + '_config.txt', 'w')
        f2 = open('Temp.txt','r')
#       f.close()

        lines = f2.readlines()
        for line in lines:    #读每一行的配置
            if "#" in line:
                new_configure.write(line)
            elif "interface GigabitEthernet" in line:   #找寻端口配置命令,并生成配置命令
                new_configure.write(line)
            elif "traffic-policy P5M inbound" in line:  #找寻对应的端口下是否有限速的配置命令,并生成配置命令
                new_configure.write(" undo traffic-policy inbound\n traffic-policy P5Mnew inbound\n ")
            elif "traffic-policy P10M inbound" in line:  #找寻对应的端口下是否有限速的配置命令,并生成配置命令
                new_configure.write(" undo traffic-policy inbound\n traffic-policy P10Mnew inbound\n ")

        f.close()
        new_configure.close()
        print(host+"finish")

except Exception as e:
    print ("The Script failed to login")
    print (str(e))

本文固定链接: http://t.yjsec.com/index.php/2018/02/08/330/ | 下一站

该日志由 admin 于2018年02月08日发表在 Python 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: python pexpect | 下一站

python pexpect:等您坐沙发呢!

发表评论

快捷键:Ctrl+Enter