通过Python代码可以轻松实现网络批量化操作,相对于ansible或者其他的方式来看。Python可能是一个比较轻松实现的方式。
例如配置备份,批量配置等操作,不废话直接上代码
测试代码;
#!/usr/bin/python
#conding=utf-8
import pexpect
import os
import sys
import time
import re
ii = ['10.0.0.1',]
for host in ii:
user = 'admin'
password = 'admin'
ssh_newkey = 'Are you sure you want to continue connecting'
c = pexpect.spawn('ssh -l %s %s' % (user, host))
如果想知道整体输入和输出情况 可以增加spaw里面的参数
c = pexpect.spawn('ssh -l %s %s' % (user, host),logfile=sys.stdout)
i = c.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if i == 0: # Timeout
pass
if i == 1: # SSH does not have the public key. Just accept it.
c.sendline('yes')
c.expect('password: ')
i = c.expect([pexpect.TIMEOUT, 'password:'])
if i == 0: # Timeout
print 'ERROR!'
print 'SSH could not login. Here is what SSH said:'
c.sendline(password)
c.sendline('\n')
time.sleep(1)
c.sendline('super')
time.sleep(0.2)
c.expect(['Password', pexpect.EOF, pexpect.TIMEOUT])
c.sendline('admin')
time.sleep(0.2)
c.sendline('display arp | in 10.0.0.') 命令根据自己需求换
c.sendline(" ")
c.sendline('quit')
c.expect(['quit', pexpect.EOF, pexpect.TIMEOUT])
print c.before
这一段是为批量执行
#!/usr/bin/python
#conding=utf-8
import pexpect
import os
import sys
import time
import re
ii = []
for number in range(17,18):
ii.append('10.0.0.' + str(number))
class sss:
def __init__(self,ii):
self.ii = ii
for self.host in self.ii:
self.user = '用户名'
self.password = '密码'
ssh_newkey = 'Are you sure you want to continue connecting'
self.c = pexpect.spawn('ssh -l %s %s' % (self.user, self.host))
self.i = self.c.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if self.i == 0: # Timeout
pass
if self.i == 1: # SSH does not have the public key. Just accept it.
self.c.sendline('yes')
self.c.expect('password: ')
self.i = self.c.expect([pexpect.TIMEOUT, 'password:'])
if self.i == 0: # Timeout
print 'ERROR!'
print 'SSH could not login. Here is what SSH said:'
self.c.sendline(self.password)
self.c.sendline('\n')
time.sleep(1)
注释的这几行是为了h3c这种aaa认证使用super密码的方式进行登入
# c.sendline('super')
# time.sleep(0.2)
# c.expect(['Password', pexpect.EOF, pexpect.TIMEOUT])
# c.sendline(super密码)
time.sleep(0.2)
def peizhi(self,conf):
self.c.sendline('sys')
self.c.sendline(conf)
self.c.sendline('quit')
self.c.sendline('quit')
#self.c.interact()
self.c.expect([pexpect.EOF, pexpect.TIMEOUT])
print self.c.before
def configure(self):
c.sendline('display current-configuration ' + '\n')
c.sendline(" ")
c.sendline('quit')
print c.before
c.expect([ pexpect.EOF, pexpect.TIMEOUT])
# print c.before 想看具体的 可以取消这个注释
f = open(('/home/peizhi/ssh/'+host),'w')
f.write(c.before)
f.close()
ss = 'dos2unix /home/peizhi/ssh/' + host
os.system(ss)
c.sendline('quit')
conf = 'info-center loghost 172.16.3.43'
for h in ii:
try:
print h
m = sss({h:1}) 主要是为了for循环
m.peizhi(conf)
except:
print'+++++++++++++++++++++++++++++++++++++++'