telnet远程登录脚本
场景描述:有多台路由器,需要统一进行相关操作,比如统一shutdown局域口0/1。
如果每台路由器都进行telnet远程登录操作,即繁琐又麻烦。
因此有了以下登录操作脚本,python代码如下:
from telnetlib import Telnet
import time
import logging
'''author fzuim'''
'''
路由器telnet执行远程命令类
指令统一采用encode UTF-8编码方式
使用方式:
1. 在.py同路径下,新建route_list.txt、cmd.txt
2. 在route_list.txt一行行输入顺序连接的IP列表
3. 在cmd.txt一行行输入顺序执行的命令
4. python 直接编译py文件运行即可
note: 适用于每个路由器登录和特权账号密码一致的情况,若不一致得改造下代码。
'''
class RouteTelnetClient():
def __init__(self):
self.tn = Telnet()
def login_host(self, host, username, password, enable=None, shret=True):
try:
self.tn.open(host, port=23)
except:
logging.warning('%s网络连接失败' %host)
return False
self.tn.read_until(b'Username:', timeout=1)
self.tn.write(b'\n')
self.tn.write(username.encode() + b'\n')
if shret:
rely = self.tn.expect([], timeout=1)[2].decode().strip()
print(rely)
self.tn.read_until(b'Password:', timeout=1)
self.tn.write(password.encode() + b'\n')
if shret:
rely = self.tn.expect([], timeout=1)[2].decode().strip()
print(rely)
if enable is not None:
self.tn.write(b'enable\n')
self.tn.write(enable.encode()+b'\n')
if shret:
rely = self.tn.expect([], timeout=1)[2].decode().strip()
print(rely)
time.sleep(1)
rely = self.tn.read_very_eager().decode()
if 'Login invalid' not in rely:
logging.warning('%s->登陆成功' %host)
return True
else:
logging.warning('%s->登陆失败,用户名或密码错误' %host)
return False
def do_cmd(self, cmds):
try:
with open(cmds) as cmd_obj:
for cmd in cmd_obj:
self.tn.write(cmd.encode().strip() + b'\n')
time.sleep(2)
rely = self.tn.read_very_eager().decode()
logging.warning('命令执行结果:\n %s' %rely)
except IOError as e:
logging.error('open %s failed:%s.\n' %(cmd, e))
def logout_host(self):
self.tn.close()
if __name__ == '__main__':
username = 'admin'
password = 'admin!'
enable = 'admin%'
lists = 'route_list.txt'
cmds = 'cmd.txt'
telnet_client = RouteTelnetClient()
try:
with open(lists, 'rt') as list_obj:
for route in list_obj:
info_list = route.split(',')
name = info_list[0];
host = info_list[1];
print(u'准备链接[%s][%s]... \n' %(name, host))
input(u'是否开始?(回车开始)')
if telnet_client.login_host(host.strip(), username, password, enable):
telnet_client.do_cmd(cmds)
telnet_client.logout_host()
time.sleep(2)
else:
logging.error('telnet %s login failed.\n' %host)
except IOError as e:
logging.error('open %s failed:%s.\n' %(lists, e))