python网络自动化_python 网络设备远程自动化

telnetlib 远程telnet库 paramiko 远程ssh库

ssh批量按时备份网络设备配置ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:

ssh.connect(

hostname=host,

username=user,

password=passwd,

port=22,

pkey=None, look_for_keys=False,

timeout=3, allow_agent=False)

remote_conn = ssh.invoke_shell()

time.sleep(0.1) # 设置间隔

for cmdline in cmdlist:

remote_conn.send("%s\n" % cmdline)

time.sleep(0.5)

output = remote_conn.recv(1000).decode()

devname = re.findall(r'\<(.*)\>.*',output)[0] #正则导入主机名

remote_conn.send('rename startup.cfg %s-%s.cfg-%s\n' % (devname,host,date))

time.sleep(1)

remote_conn.send('save\n') #保存设备当前配置

time.sleep(0.5)

save = remote_conn.recv(1000).decode()

if save.find('written') > -1:

remote_conn.send("Y\n")

time.sleep(1)

# print(remote_conn.recv(1000))

remote_conn.send("\n")

# print(remote_conn.recv(1000))

remote_conn.send("Y\n")

# time.sleep(5)

# print(remote_conn.recv(1000))

py2 telnet远程执行import telnetlib

import re,time,datetime

import sys

reload(sys)

sys.setdefaultencoding("utf-8")

DEBUG = False # False 读取host.txt列表主机

cmdlist = [

"ftp 36.27.209.xx",

"ftp",

"ftpxxx",

"cd net_config"

]

def run(host):

now = datetime.datetime.now()

today = now.strftime('%Y%m%d')

logdate = now.strftime("%b %d %H:%M:%S")

try:

telnetsession = telnetlib.Telnet(host,timeout=10) # 实例化telnet对象,建立一个主机连接

#print (telnetsession.timeout)

#telnetsession.set_debuglevel(1) # 开启调试,按需开启,方便判断

telnetsession.write(user + "\n")

telnetsession.read_very_lazy()

telnetsession.write(pwd + "\n")

#登录认证

# 如果登录成功,则出现类似,使用UsermodTag来进行捕获

response = telnetsession.read_until('>')

devname = re.findall(r'\<(.*)\>.*',response)[0] #正则导入主机名

#print(devname)

if response.find('>') > -1:

print("INFO:\t%s\t[\033[1;32m%s\033[0m] Login successfully ..." % (logdate, host))

for cmdline in cmdlist:

telnetsession.write("%s\n" % cmdline)

telnetsession.read_very_lazy()

response = telnetsession.read_until('changed')

#read_until()来判断缓冲区中的数据是否有想要的内容,如果没有就等待

telnetsession.write("put startup.cfg %s-%s-%s.cfg\n" % (devname,host,today))

telnetsession.close()

except Exception as e:

print(e, type(e))

finally:

# 执行完毕后,关闭连接

print("INFO:\t%s\t[\033[1;32m%s\033[0m] Session Close ..." % (logdate, host))

telnetsession.read_until('complete')

telnetsession.write("quit\n")

telnetsession.close()

if __name__ == '__main__':

### 配置登录信息

user = 'admin'

pwd = raw_input("输入密码:")

host = '192.168.16.2'

if not DEBUG:

with open("host.txt") as f:

for host in f:

h = host.strip()

run(h)

else: #测试

run(host)

ssh 批量远程执行例2import paramiko

import time

import pprint

import socket

import re

DEBUG = True # False 读取host.txt列表主机

user = 'root'

passwd = input('输入密码: ')

hostlist = [

'account-98-1',

'account-98-10',

]

cmdlist = [

"ls /root",

"touch /tmp/paramiko.py"

]

def run(host):

date = time.strftime("%b %d %H:%M:%S", time.localtime())

print("INFO:\t%s\t[\033[1;32m%s\033[0m] Trying to connect ..." % (date, host))

paramiko.util.log_to_file('paramiko.log')

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

count = 0

try:

ssh.connect(

hostname=host,

username=user,

password=passwd,

port=22,

pkey=None, look_for_keys=False,

timeout=3, allow_agent=False)

for cmdline in cmdlist:

count += 1

stdin, stdout, stderr = ssh.exec_command(cmdline)

print("INFO:\t%s\t\033[1;34m[%s]\033[0m\t%s" %

(date, count, cmdline))

results['successful'].append(host)

except (paramiko.ssh_exception.AuthenticationException,) as e:

print("INFO:\t%s\t\033[1;31mLogin failed\033[0m\t%s" % (date, e))

results['unsuccessful'].append(host)

except (paramiko.ssh_exception.NoValidConnectionsError, socket.gaierror, socket.timeout, socket.error) as e:

print("INFO:\t%s\t\033[1;31mConnection failed\033[0m\t%s" % (date, e))

results['unsuccessful'].append(host)

except Exception as e:

print(e, type(e))

finally:

ssh.close()

if __name__ == '__main__':

results = {

'unsuccessful': [],

'successful': [],

}

if not DEBUG:

with open("host.txt") as f:

for host in f:

result = re.match(r'(\w+)\-(.*)', host).groups()

result = (list(result)) # 主机名和编号,将元组结果转列表

result.reverse() # 反转列表 account-98-1 -> 98-1.account

domain = '.'.join(result) # 拼接

run(domain)

else:

print("DEBUG:\tTest")

for host in hostlist:

result = re.match(r'(\w+)\-(.*)', host).groups()

result = (list(result)) # 主机名和编号,将元组结果转列表

result.reverse() # 反转列表

domain = '.'.join(result) # 拼接

run(domain)

pprint.pprint(results)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值