python文件

# --*--coding:utf-8--*--

from telnetlib import Telnet
import re,time,datetime,os,threading,sys

#获取脚本目录
if __name__!='__main__':
    present_dir=os.path.dirname(__file__)
else:
    present_dir=os.getcwd()
#获取当前日期
nowdate=datetime.datetime.now().strftime('%Y%m%d')

#当天日期的目录路径
nowday_dir='%s/%s'%(present_dir,nowdate)

#创建当天日期的目录
if not os.path.isdir(nowday_dir):
    os.mkdir(nowday_dir)

#创建配置文件
if not os.path.exists('%s/config.txt'%present_dir):
    file=open('%s/config.txt'%present_dir,'w')
    file.close()

#华为设备执行命令函数
def execute_hw(address,port,account,password):
    '''address:设备地址
    cmd:执行的命令列表
    account:账号
    password:密码
    例子:print(excute_hw('110.196.22.81',['dis version',]))
    '''
    #此处服务器地址
    tn=Telnet(address,port)
    try:
        #此处是账号密码
        #tn.read_until(b"Username:",timeout=None)
        print('用户名:'+account)
        #tn.read_until(b'login: ',timeout=None)
        tn.read_until(b'login: ',timeout=1)
        #tn.write(account.encode('ascii')+b'\n')
        tn.write(account.encode('ascii') + b'\n')
        print('密码:'+password)
        #tn.read_until(b'Password:',timeout=None)
        tn.read_until(b'Password: ',timeout=1)
        #tn.write(password.encode('ascii')+b'\n')
        tn.write(password.encode('ascii') + b'\n')
        text=tn.read_until(b">",timeout=None).decode()
        #获取设备名称
        devicename=re.findall(r'<(.+)>',text)[0]
        print('设备名称:'+devicename)
        #一次显示全部
        #tn.write(b"screen-length 0 temporary"+b'\n')
        tn.write(b"screen-length disable"+b'\n')
        text+=tn.read_until(b">",timeout=1).decode()
        #获取配置
        print("获取配置.....")
        tn.write(b"sys"+b'\n')
        tn.write(b"dis cur"+b'\n')
        time.sleep(2)
        flag=True
        while flag:
            tmp=tn.read_very_eager()
            if 'Error:' in tmp.decode():
                text=text+tmp.decode()
                tn.close()
            elif '---- More ----' in tmp.decode():
                text=text+tmp.decode()
                tn.write(b' ')
                time.sleep(0.5)
            elif tmp==b'' and (text[-1:]=='>' or text[-1:]==']'):
                flag=False
            else:
                text=text+tmp.decode()
                time.sleep(2)
    except:
        if 'devicename' not in dir():
            devicename = "获取不到名字"
            text="获取配置失败!"
    finally:
        tn.close()
        #写入配置
        filename='%s-%s.txt'%(address,devicename)
        with open('%s/%s'%(nowday_dir,filename),'w') as f:
            f.write(text)
    return True

#多线程程序
class myThread(threading.Thread):
    def __init__(self,address,port,account,password):
        threading.Thread.__init__(self)
        self.address=address
        self.port=port
        self.account=account
        self.password=password
    def run(self):
        #print(self.address,self.port,self.account,self.password)
        execute_hw(self.address,self.port,self.account,self.password)

#获取配置文件
with open('%s/config.txt'%present_dir) as f:
    myconfig=f.read()

#创建多线程
thread_list=[]
for line in myconfig.splitlines():
    if line:
        address,port,account,password=re.split(r'\s+',line)[:4]
        thread_list.append(myThread(address,port,account,password))

count1=0
count2=0

while True:
    thread_list[count2].start()
    count2+=1
    if count2%200==0:
        while True:
            thread_list[count1].join()
            count1+=1
            if count1==count2:
                break
    if count2>=len(thread_list):
        while count1<count2:
            thread_list[count1].join()
            count1+=1
        break
import logging
import telnetlib
import time
import re

class TelnetClient():
    def __init__(self,):
        self.tn = telnetlib.Telnet()

    # 此函数实现telnet登录主机
    def login_host(self,host_ip,username,password):
        try:
            # self.tn = telnetlib.Telnet(host_ip,port=23)
            self.tn.open(host_ip,port=23)
        except:
            logging.warning('%s网络连接失败'%host_ip)
            return False
        # 等待login出现后输入用户名,最多等待10秒
        self.tn.read_until(b'login: ',timeout=10)
        self.tn.write(username.encode('ascii') + b'\n')
        # 等待Password出现后输入用户名,最多等待10秒
        self.tn.read_until(b'Password: ',timeout=10)
        self.tn.write(password.encode('ascii') + b'\n')
        text=self.tn.read_until(b">", timeout=2).decode()
        devicename = re.findall(r'<(.+)>', text)[0]
        print('设备名称:' + devicename)
        self.tn.write(b"screen-length disable"+b'\n')
        self.tn.write(b"sys" + b'\n')
        # 延时两秒再收取返回结果,给服务端足够响应时间
        time.sleep(2)
        # 获取登录结果
        # read_very_eager()获取到的是的是上次获取之后本次获取之前的所有输出
        command_result = self.tn.read_very_eager().decode('ascii')
        if 'Login incorrect' not in command_result:
            logging.warning('%s登录成功'%host_ip)
            return True
        else:
            logging.warning('%s登录失败,用户名或密码错误'%host_ip)
            return False

    # 此函数实现执行传过来的命令,并输出其执行结果
    def execute_some_command(self,command):
        # 执行命令
        self.tn.write(command.encode('ascii')+b'\n')
        time.sleep(2)
        # 获取命令结果
        command_result = self.tn.read_very_eager().decode("ascii","ignore")
        #logging.warning('命令执行结果:\n%s' % command_result)
        print(command_result)

    # 退出telnet
    def logout_host(self):
        self.tn.write(b"exit\n")

if __name__ == '__main__':
    host_ip = '192.168.1.1'
    username = 'admin'
    password = ''
    command = 'dis cur'
    telnet_client = TelnetClient()
    # 如果登录结果返加True,则执行命令,然后退出
    if telnet_client.login_host(host_ip,username,password):
        telnet_client.execute_some_command(command)
        telnet_client.logout_host()

config配置文件

192.168.10.1 23 admin admin
192.168.10.2 23 admin admin
192.168.10.3 23 admin admin
192.168.10.4 23 admin admin
192.168.10.5 23 admin admin
192.168.10.6 23 admin admin