Python 脚本备份华为交换机

  • 转载请注明出处

需要调用的库:

import telnetlib
import datetime
import time

需要了解的telnetlib函数

telnetlib.Telnet #telnet 连接
telnetlib.read_until #等待字符出现
telnetlib.write #输入命令
telnetlib.read_very_eager #读取页面所以内容

完整代码

import telnetlib
import datetime
import time



def login_telnet(Host, username, password, finish, commands):

        tn = telnetlib.Telnet(Host, port=23, timeout=20) #连接
        tn.set_debuglevel(2)

        tn.read_until(b'Username:') #等待Username出现
        tn.write(username.encode('ascii') + b"\n") #输入username

        tn.read_until(b'Password:')
        tn.write(password.encode('ascii') + b"\n")

        tn.read_until(b'')
        file_object = open(filepath, 'wb')
        for command in commands:
                tn.write(command.encode('ascii') + b"\n")
                time.sleep(2)
                for i in range(0, 100): #输入100次空格
                        time.sleep(1)
                        tn.write(b" ")
                time.sleep(1)
                result = tn.read_very_eager()

                file_object.write(result)
                print('Finish.............')


        file_object.close()
        tn.close()




if __name__ == '__main__':
        Host = ''#账号
        username = ''#账号
        password = ''#密码
        finish = ''#等待此字符出现(可不输入)
        date = datetime.datetime.now()#获取系统当前时间
        filepath = '/home/%s.txt'%date#保存路径
        commands = ['dis cur']#输入命令
        login_telnet(Host, str(username), password, finish, commands) # 主机 用户 密码 等待字符 命令

特别注意

当python把字符串输入交换机时需要把字符串转换成 'ascii' 格式

tn.write(username.encode('ascii') + b"\n") #转成ascii格式

发表评论

电子邮件地址不会被公开。 必填项已用*标注