telnet登录脚本
#!/usr/bin/env python
#coding=utf-8
import telnetlib,sys,os,time
def login_telnet(Host, username, password, finish, commands):
#import telnetlib,sys,os,time
tn = telnetlib.Telnet(Host, port=23, timeout=20)
#tn.set_debuglevel(2)
tn.read_until('Username:')
tn.write(username + '
')
tn.read_until('Password:')
tn.write(password + '
')
tn.read_until(finish)
file_object=open(filepath,'wb')
for command in commands:
tn.write('%s
' % command)
for i in range(0,5):
tn.write(' ')
time.sleep(1)
result=tn.read_very_eager()
file_object.write(result)
print ('Finish.............')
tn.write('
')
tn.read_until(finish)
file_object.close()
tn.close()
def filename_change():
#import sys,time,os
localtime=time.strftime('%Y%m%d%H%M',time.localtime(time.time()))
if os.path.exists(filepath):
filename=os.path.split(filepath)
filenewname=filename[1].split('.')
os.chdir(filename[0])
os.rename(filename[1],filenewname[0]+'_'+localtime+'.'+filenewname[1])
if __name__=='__main__':
Host = '10.2.0.1'
username = 'xuewenlong'
password = 'xuewenlong@123'
finish = '<router>'
filepath = '/home/data/router_result.txt'
commands = ['display device','display temperature all','display memory-usage','dis interface GigabitEthernet 0/0/3','display cpu-usag
e']
login_telnet(Host, username, password, finish, commands)
filename_change()
ssh登录脚本
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
import time
import sys,os
import shutil
def ssh_login(Host, Username, Password, Commands):
ssh = pexpect.spawn('ssh %s@%s' %(Username, Host))
res = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
if res == 0:
ssh.sendline(Password)
elif res == 1:
ssh.sendline('yes')
ssh.expect('password:')
ssh.sendline(Password)
ssh.expect([finish,pexpect.TIMEOUT,pexpect.EOF])
for cmd in Commands:
print "finish....."
ssh.sendline(cmd)
for i in range(0,5):
ssh.sendline(' ')
res = file(filepath,'wb')
ssh.logfile_read = res
ssh.sendline('quit')
ssh.read()
ssh.close()
res.close()
def filename_change(filepath):
localtime=time.strftime('%Y%m%d%H%M',time.localtime(time.time()))
dirtime=time.strftime('%Y%m',time.localtime(time.time()))
filename=os.path.split(filepath)
filedir=filename[0]+'/'+dirtime
isExists=os.path.exists(filedir)
if not isExists:
os.makedirs(filedir)
filenewname=filename[1].split('.')
shutil.move(filepath, filedir)
os.chdir(filedir)
#os.rename(filename[1],filenewname[0]+'_'+localtime+'.'+filenewname[1])
if __name__=='__main__':
Host = '192.168.4.3'
Username = 'xuewenlong'
Password = 'xuewenlong@123'
Commands = ['display device','display temperature','display memory-usage','display cpu-usage','dis int gig0/1/0']
finish = '<HZ-YD-RT-LNS-1>'
filepath = '/home/data/lns1hz.log'
ssh_login(Host, Username, Password, Commands)