#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os,sys,time,shutil,re
from _ast import Num
from django.db.models.sql.datastructures import Join
'''
---------------------------
此脚本用于之前学习内容的回顾
装饰器还需要多看,目前还是不是很清楚
类的继承
property需要学习
抽象方法/私有字段/私有方法/静态字段/静态方法
__call__方法
__del__方法
---------------------------
'''
#-------------------递归例子---------------------
'''
#函数
def fun2(n):
result = n
for i in range(1,n):
result *= i
return result
print 'fun2',fun2(5)
#递归
def fun3(n):
if n == 1:
return 1
else:
return n*fun3(n-1)
print 'fun3',fun3(5)
def fun(n):
if n == 1:
return 1
else:
return n+fun(n-1)
print fun(5)
def fun1(x):
if x == 0 or x ==1:
return 1
else:
return fun1(x-1) + fun1(x-2)
print fun1(5)
如果说兔子在出生两个月后,就有繁殖能力,在拥有繁殖能力之后,这对兔子每个月能生出
一对小兔子来。假设所有兔子都不会死去,能够一直干下去,那么一年之后可以繁殖多少对
兔子呢?
def tuzi(x):
if x==1 or x==2:
return 1
else:
return tuzi(x-1)+tuzi(x-2)
print tuzi(5)
'''
#-------------------递归 遍历目录下所有文件---------------------
'''
#----------列表推导式列出所有文件
path = 'd:/python'
os.chdir(path)
a = [i for i in os.listdir(path) if os.path.isfile(i)]
for x in a:
print x
#等同下面
for i in os.listdir('d:/python'):
a = os.path.join('d:/python',i)
print os.path.isfile(a)
if os.path.isfile(i):
print i
path = 'd:/python'
os.chdir(path)
a = [i for i in os.listdir(path) if os.path.isfile(i) and os.path.splitext(i)[1] =='.zip']
print a
path = 'd:/python'
#----------递归方式
#可采用os.path.join拼接路径的方式,来确认完整路径,避免使用路径切换,os.chdir
def scan(path):
for file in os.listdir(path):
file_dir = os.path.join(path,file)
if not os.path.isdir(file_dir):
print file_dir
else:
scan(file_dir)
scan(path)
#----------os.walk方式
g = os.walk('d:/python')
for path,folder,filelist in g:
print filelist
for filename in filelist:
print os.path.join(path,filename)
'''
#------------------文件夹整理-----------------------
'''
def file_summary(path):
for file in os.listdir(path):
file_dir = os.path.join(path,file)
if os.path.isdir(file_dir):
file_summary(file_dir)
else:
file_name = ''.join(re.findall('201\d{5}',file))
Folder_name = os.path.join(path,file_name)
try:
if not os.path.exists(Folder_name):
os.mkdir(Folder_name)
wjy_num += 1
try:
if file_dir not in os.listdir(Folder_name):
print file_dir
shutil.move(file_dir,Folder_name)
except:
print 'error'
file_num += 1
except:
print '没找到日期'
file_summary(path)
'''
# print '''
# -------------------------------------------------------
# 此脚本用于整理文件,按图片名日期进行分类,每个日期建
# 一个新的文件夹,将同一天的文件放入文件夹中
# -------------------------------------------------------
# '''
'''
def fodler_time_fengnei(path):
wjy_num = 0
file_num = 0
os.chdir(path)
for i in os.listdir(path):
#print i
Folder_file = ''.join(re.findall('201\d{5}',i))
#print Folder_file
try:
#lock.acquire()
if not os.path.exists(Folder_file):
os.mkdir(Folder_file)
wjy_num += 1
try:
if i not in os.listdir(Folder_file):
shutil.move(i,Folder_file)
except:
print 'error'
#lock.release()
file_num += 1
except:
print '没找到日期'
print '处理了%d个文件'%file_num
print '创建了%d个文件夹'%wjy_num
print '分类完成'
#print os.getcwd()
def folder_vedio(path):
os.chdir(path)
#os.walk 得到一个三元数组:路径,路径下的文件夹,文件
for i,k,v in os.walk(path):
print i,k,v
#迭代文件夹目录
for folder in k:
#进入每个文件夹
os.chdir(folder)
#迭代当前文件夹下的文件
for img in os.listdir(os.curdir):
print img
try:
ext = img.split('.')[1] #得到扩展名
print ext
except:
print 'error'
if ext != 'jpg': #如果不是图片文件
shutil.move(img, os.pardir) #移动到上一级目录
os.chdir(os.pardir)
#此函数用于将文件夹下的所有文件移动到指定的目录中,
#目前只有一层目录功能 2016/12/27更新
def file_move(path,dst):
os.chdir(path) #这里一定要先进入到需要整理的目录中
for i,k,v in os.walk(path):
print i,k
for folder in k:
try:
print os.getcwd()
os.chdir(folder)
for file in os.listdir(os.curdir):
shutil.move(file, dst)
except Exception,e:
print e
os.chdir(os.pardir)
#以下用于移动文件,已成功实现所需功能 2016/12/28
def file_move(path,dst):
os.chdir(path)
n = 1
#dst = 'd:\\pooto\\p'
#这里用os.walk产生一个生成器,再通过迭代,列出目录下所有的子目录和文件
#os.walk以递归的方式遍历当前目录下的所有文件和目录
for path1,file_dir,fs in os.walk(path):
# print 'PATH 第%d次:'%n,path1
# print 'DIR:第%d次:'%n,file_dir
# print 'FS第%d次:'%n,fs
#确认当前目录下是否有文件,没有跳过
if fs==[]:
pass
#print '空的'
else:
file_num = 0
try:
#如果有文件,迭代一下
for file in fs:
#进入目录
os.chdir(path1)
#print '当前路径是: '+os.getcwd()+', 当前文件是: '+file
ext = file.split('.')[-1] #取最后一个就是扩展名
#print ext
if ext == 'jpg' or ext =='png':
try:
shutil.move(file,dst) #移动到指定目录
#print 'move was ok'
file_num += 1 #统计移动文件的个数
except Exception,e: #出错了,提示原因
#print e
print u'移动文件出错了,快查一下原因'
#shutil.move(file,del_dir)
except:
print u'迭代序列出错了'
print u'移动了%d个文件'% file_num
os.chdir(os.pardir) #当前目录完成了,跳回主目录,进行下一次迭代目录
n += 1
if __name__ == '__main__':
-------------------------------------------------
请选择你需要的功能:
1. 对图片按名称分组
2. 对图片按后缀分组
3. 将文件移动到另一目录中
-------------------------------------------------
select1 = raw_input(':')
start_time = time.time()
if select1 == '1':
#lock = threading.Lock()
path = raw_input(u'如:g:/software/DIM :').strip()
fodler_time_fengnei(path)
# t1 = threading.Thread(target=fodler_time_fengnei,args=(path,))
# t2 = threading.Thread(target=fodler_time_fengnei,args=(path,))
# t3 = threading.Thread(target=fodler_time_fengnei,args=(path,))
elif select1 =='2':
pass
elif select1 == '3':
print u'源文件夹:'
path = raw_input(u'如:g:/software/DIM :').strip()
dst = raw_input(u'目标文件夹:').strip()
file_move(path, dst)
# 多线程没什么效果
# t1 = Thread(target=file_move,args=(path,dst))
# t2 = Thread(target=file_move,args=(path,dst))
# t3 = Thread(target=file_move,args=(path,dst))
# p1.start()
# print 't1'
# t2.start()
# print 't2'
# t3.start()
# print 't3'
end_time = time.time()
print u'总共花了%.2f秒'%(end_time-start_time)
# path = raw_input('[eg:g:/software/DIM] :').strip()
# #os.chdir(path)
# file_num = 0
# wjy_num = 0
# # folder_vedio(path)
# fodler_time_fengnei(path)
# print '总共整理了%d个文件'%file_num
# print '总共创建了%d个文件夹'%wjy_num
'''
#------------------局部变量-----------------------
'''
var = 1
def a():
global var
var += 1
var1 = 2
# print var
def b():
print var1
nolocal #这里2.7好像有问题,3.x好像是好的
var1 = 5
#print var1
b()
a()
'''
#------------------------Pexpect练习----------------------
'''
用于登录Cisco设备并获取相关信息,每次一个命令,完成后自动退出
适用于Linux
'''
'''
def get(pe,cmd):
login = 'telnet %s' % pe
username = 'pingtest'
password = 'pwdtest'
tn = pexpect.spawn(login,timeout = 300)
index = tn.expect(["Username",pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
tn.expect('Username:')
tn.sendline(username)
tn.expect('Password:')
tn.sendline(password)
tn.expect('#')
tn.sendline(cmd)
tn.sendline(' ')
tn.expect('#')
result = tn.before
tn.sendline('exit')
print result
elif index == 1:
print 'pexpect.EOF'
else:
print 'pexpect.TIMEOUT'
if __name__ == '__main__':
tupe1 = {
'Mon':'星期一',
'Tue':'星期二',
'Wen':'星期三',
'Thu':'星期四',
'Fri':'星期五',
'Sat':'星期六',
'Sun':'星期天'
}
wenday = time.strftime('%a')
xiqi = tupe1[wenday]
while True:
print '\n'
pe = (raw_input('请输入你需要登录的PE[退出请用q]:')).strip()
print '\n'
if pe == 'q':
break
else:
cmd = (raw_input('请输入你需要执行的命令[退出请用q]:')).strip()
if cmd == 'q':
break
print '\n\n'
print '当前查询时间:%s'%((time.strftime('%Y/%m/%d %H:%M:%S'))+' '+ xiqi)
print '-----------------------------------------------------'
print '\n'
get(pe,cmd)
'''
#------------------------装饰器实验1----------------------
# def out(fun):
# def watter():
# print '之前出现'
# fun()
# print '之后出现'
# return watter
#
# @out
# def fun1():
# print '这是Fun1的内容'
#
# fun1()
# ---------带参数的装饰器
# def out(fun):
# def watter(args):
# print '之前出现'
# fun(args)
# print '之后出现'
# return watter
#
# @out
# def fun1(args):
# print '这是Fun1的内容',args
#
# fun1(100)
#---------带返回的装饰器
# def out(fun):
# def watter(args):
# print '之前出现'
# a =fun(args)
# print '之后出现'
# print a
# return watter
#
# @out
# def fun1(args):
# return u'这是Fun1的内容',args
#
# fun1(100)
#-----下面这个例子很好说明的装饰器的运行
# def timeslong(func):
# def call():
# start = time.clock()
# print("It's time starting ! ")
# func()
# print("It's time ending ! ")
# end = time.clock()
# return "It's used : %s ." % (end - start)
# return call
#
# @timeslong
# def f():
# y = 0
# for i in range(10):
# y = y + i + 1
# print(y)
# return y
#
# print(f())
#------------------------property---------------------
# class A:
# def __init__(self):
# print '这是A的Self'
#
# def B(self):
# print '这是B的方法'
#
# @property
# def C(self):
# # print '这是C的方法'
# return '这是C的方法'
#
# a = A()
# print a
# print a.B()
# print a.C
#
#
# class C:
# def __init__(self):
# self._x = None
#
# @property
# def x(self):
# """I'm the 'x' property."""
# return self._x
#
# @x.setter
# def x(self, value):
# self._x = value
#
# @x.deleter
# def x(self):
# del self._x
#
#
# c1 = C()
# c1.x = 3
# print c1.x
#########################################################
#------------------------抽象方法---------------------
#抽象类抽象方法==接口
from abc import ABCMeta,abstractmethod
# class Bar:
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def get(self):
# raise 'no define get '
#
# class Car(Bar):
# def __init__(self):
# print '这是一个Car的类'
#
# # def get(self):
# # print 'aaa'
#
# car = Car()
# class Bar:
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def Fun(self):
# pass
#
# class Foo(Bar):
# def __init__(self):
# print '__init__'
#
# # def Fun(self):
# # print '告警'
#
# f = Foo()
# f.Fun()
#########################################################
#------------------------私有字段/方法---------------------
# class Bar:
# def __init__(self):
# self.__x = 10
#
# def __get(self):
# print '这是私有方法'
# #可以通过动态方法调用私有方法
# def show(self):
# print self.__get()
#
# b = Bar()
# print b._Bar__x #强制使用类的方式来访问私有方法
# print b.show()
#------------------------静态字段/方法---------------------
# class Bar:
# name = 'liyang'
# @staricmethod
# def hello():
# print 'Hello'
#
# b = Bar()
# print b.name
# print b.hello()
# 静态字段和静态方法无需实例化,可通过用类来调用
#########################################################
#------------------------静态字段/方法---------------------
#__call__ 最后执行
#__del__ 什么时候使用,直接用对象加括号就可以调用了
# class Bar:
# def __init__(self):
# print '这是__init__'
#
# def __call__(self):
# print '这是__call__'
#
# def __del__(self):
# print '我就要被删除了'
#
# def show(self):
# print '这是一个显示的函数'
#
# b = Bar()
# print b
# print b() #调用call方法
# print b.show()
#########################################################
#------------------------类的继承---------------------
#新式类必须加object,同时多重继承是广度优先,经典类是深度优先
# class A(object):
# def __init__(self):
# print '这是A的__init__'
#
# def show(self):
# print '这是显示A的类'
#
# class B(A):
# def __init__(self):
# #A.__init__(self)
# super(B,self).__init__() #这里的super值为当前类,主类必须是新式类
# print '这是B的__init__'
#
# class C(A):
# def __init__(self):
# print '这是C的__init__'
#
# def show(self):
# print '这是显示C的类'
#
# class D(B,C):
# def __init__(self):
# print '这是D的__init__'
#
#
# # b1 = B()
# # print b1
#
# d1 = D()
# print d1
# print d1.show()
#--------------------使用super也可以在经黄类中避免深度优先的问题------------------
# class A():
# def __init__(self):
# print '这是A的__init__'
#
# def show(self):
# print '这是显示A的类'
#
# class B(A):
# def __init__(self):
# #A.__init__(self)
# super().__init__() #这里的super,可以避免深度优先的问题
# print '这是B的__init__'
#
# class C(A):
# def __init__(self):
# print '这是C的__init__'
#
# def show(self):
# print '这是显示C的类'
#
# class D(B,C):
# def __init__(self):
# print '这是D的__init__'
#
# b1 = B()
# print b1
# d1 = D()
# print d1
# print d1.show()
#########################################################
'''
------------------------------
字符编码:ASCII/Unicode/UTF-8
decode的作用是将其他编码的字符串转换成unicode编码,
encode的作用是将unicode编码转换成其他编码的字符串,
Unicode
Unicode-----encode---->UTF
------------------------------
'''
#------------------------编码学习---------------------
# name = '李明'
# print '第一次',name
# if not isinstance(name,unicode):
# name = name.decode('utf-8')
# print name
#
#########################################################
# import datetime
# #显示当前日期
# print datetime.date.today()
# print datetime.date.today() - datetime.timedelta(days = 2)
# #显示指定日期
# print datetime.date(2015, 4, 2)
#
# print datetime.time(1,2,3)
#------------------------生成器---------------------
# def a():
# for i in range(10):
# yield i
#
# a1 = a()
# print a1.next()
# print a1.next()
#########################################################
#--------------------Excel Into Mysql--------------------
# import pymysql
# import xlrd
#
# def xls_info():
# xls = xlrd.open_workbook('d:/bb.xls') #打开Excel
# sheets = xls.sheet_names() #获取表
# table = xls.sheet_by_name(sheets[2]) #得到需要的表名
# rows = table.nrows #获取表的总行数
# return table,rows #返回表名和行数
#
# def mysql_info():
# myconn = pymysql.Connect('127.0.0.1','root','','django') #连接Mysql
# mycur = myconn.cursor() #创建游标
# mycur.execute('set names utf8') #指定为utf8编码
# #创建表格
# # table_create = 'CREATE TABLE mysql_test(name varchar(20),ip varchar(20));'
# # mycur.execute(table_create)
# mycur.execute('desc mysql_test')
# #插入表格的命令
# insert_sql = 'insert into mysql_test values(%s,%s);'
#
# #调用上个函数的值,得到表名和行数
# table,rows=xls_info()[0],xls_info()[1]
# for i in range(0,rows): #迭代每行
# xls_line = table.row_values(i) #得到每行的信息
# print xls_line
# print mycur.execute(insert_sql,xls_line) #插入每行的数据到数据库中
# mycur.execute('select * from mysql_test')
# print mycur.fetchall()
# myconn.commit() #事务提交
# mycur.close()
# myconn.close()
#
# mysql_info()
#-------------Mysql得到字典------------------------
#!/usr/bin/env python
# encoding: utf-8
#Created on 2017年1月13日
#@author: Administrator
'''
import pymysql
def main():
try:
conn = pymysql.connect(host = '127.0.0.1', user = 'root', passwd = '', db = 'django')
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
cur.execute("select * from mysql_test")
qur_result = cur.fetchall()
cur.close()
conn.close()
# for record in qur_result:
# user = record[0]
# passwd = record[1]
except pymysql.Error,e:
print 'Mysql Error Msg:',e
#print type(qur_result)
for k in qur_result:
#print k
for i,j in k.items():
print j
if __name__ == '__main__':
main()
'''
#-------------------线程练习------------------------
import threading
from IPython.utils.io import stdin, stderr
from sys import stdout
import paramiko
'''
def Foo(args):
for i in range(10):
print i
time.sleep(1)
print '开始'
t1 = Thread(target=Foo,args = (1,))
#t1.setDaemon(True)
t1.start()
print t1.getName()
'''
#-------------------自定义线程练习------------------------
'''
class MyThread(Thread):
def run(self):
Thread.run(self)
print 'run'
for i in range(10):
print i
time.sleep(1)
def Foo(args):
print '这是我的新函数'
t1 = MyThread(target=Foo,args =(1,))
t1.start()
print t1.getName()
print t1.isDaemon()
print t1.join(3)
'''
#-------------------生产消费模型------------------------
'''
#两个类都是一样的,要用到队列,有两个判断条件,是否为空,是否为满
import Queue
class ShenChang(Thread):
def __init__(self,name,que):
self.__Name = name
self.__Que = que
Thread.__init__(self)
def run(self):
while True:
if self.__Que.full():
print '做完了,可以休息一下了'
time.sleep(1)
else:
self.__Que.put('xxx')
print self.__Name,'生产包子'
Thread.run(self)
que = Queue.Queue(maxsize=30)
for x in range(10):
name = 'alan%d'%x
s1 = ShenChang(name,que)
s1.start()
class XiaFei(Thread):
def __init__(self,name,que):
self.__Name = name
self.__Que = que
Thread.__init__(self)
def run(self):
while True:
if self.__Que.empty():
print '没有吃的了,先休息一下吧'
time.sleep(2)
else:
self.__Que.get()
print self.__Name,'吃了一个包子'
Thread.run(self)
for i in range(3):
name = 'name%d'%i
t1 = XiaFei(name,que)
t1.start()
'''
#-------------------paramiko用户名和密码------------------------
'''
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('114.28.37.23', 50022, 'root', '263!@#$%^&*()')
print 'connected..............'
while True:
cmd = raw_input('请输入你要执行的命令[退出q] : ')
if cmd == 'q':
print '\nbye---------\n------------'
sys.exit()
stdin,stdout,stderr = ssh.exec_command(cmd)
print stdout.read()
ssh.close()
'''
#-------------------paramiko Key-----------------------
'''
#在执行前要手工在目标机器上输入以下命令:
# ssh-keygen -t rsa 创建密钥
# ssh-copy-id root@114.28.37.209 将公钥Copy到服务器
private_key_path = '/root/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(private_key_path)
paramiko.util.log_to_file('paramiko.log') #加入日志
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1', 22, username='root', pkey=key)
stdin,stdout,stderr = ssh.exec_command('ls')
print stdout.read()
ssh.close()
'''
#-------------------paramiko 创建删除显示 ssh router-----------------------
'''
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#IP,Port,Username,Password='114.141.185.5',22, 'opsinfo', 'pwdops'
IP,Port,Username,Password='114.141.185.5',22, 'opsinfo', 'pwdops'
try:
ssh.connect(IP,Port,Username,Password, look_for_keys=False, allow_agent=False)
except Exception,e:
print e
print 'ssh connection established to %s' % IP
remote_conn = ssh.invoke_shell()
#print remote_conn.recv(1000)
remote_conn.send('\n')
remote_conn.send('sh ip int bri\n')
time.sleep(2)
print remote_conn.recv(10000)
#stdin,stdout,stderr = ssh.exec_command('sh ver')
# ssh.connect('1172.16.4.1', 23, 'opsinfo', 'pwdops')
# stdin,stdout,stderr = ssh.exec_command('sh ver')
#print stdout.read()
ssh.close()
'''
#-------------socket登录路由器测试-----------------
'''
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip_port =('172.16.4.1',23)
sock.connect(ip_port)
sock.send('opsinfo\n')
time.sleep(1)
sock.send('pwdops\n')
time.sleep(1)
sock.send('sh ver')
time.sleep(1)
data1 = sock.recv(1024)
time.sleep(1)
print data1
'''
#-------------------paramiko上传下载-----------------------
'''
print os.getcwd()
os.chdir('d:/')
print os.getcwd()
t = paramiko.Transport(('114.28.37.23', 50022))
t.connect(username='root', password='263!@#$%^&*()')
sftp = paramiko.SFTPClient.from_transport(t)
local_path = 'd:/lsdksmq-v2.0.0.200.zip'
base_name = os.path.basename(local_path)
remote_path = '/home/'+base_name
sftp.put(local_path,remote_path) #上传
#sftp.get(remote_path,local_path) #下载
t.close()
'''
'''
t = paramiko.Transport(('114.28.13.143', 22))
t.connect(username='root', password='111111')
sftp = paramiko.SFTPClient.from_transport(t)
print sftp.listdir('/smb')
print sftp.rename('/smb/Flow.rrd.bak','/smb/Flow.rrd.bak1')
print sftp.mkdir('/home/aa1',0755)
print sftp.listdir('/home')
'''
#-------------------paramiko+threading-----------------------
'''
用函数将Paramiko的代码包起来,再通过我线程来同时操作
def SshCmd(server,username,password,cmd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server,50022,username, password)
stdin,stdout,stderr = ssh.exec_command(cmd)
print server, '\n %s'% cmd,
print stdout.read()
ssh.close()
if __name__ =='__main__':
username = 'root'
password = '263!@#$%^&*()'
cmds = ['ls -lh /']
ips = ['114.28.37.23','114.28.37.24']
for ip in ips:
for cmd in cmds:
temp = Thread(target=SshCmd,args=(ip,username,password,cmd))
temp.start()
'''
#-------------------threading 异步模型-----------------------
'''
import threading
def shengchang():
print u'P:做包子………………'
event.wait()
event.clear()
print u'P:做包子'
time.sleep(3)
print u'P:你的包子做好了'
event.set()
def xiaofei():
print u'C:买包子去………………'
event.set()
time.sleep(2)
print u'C:等做包子……………… '
#print event.wait()
while True:
if event.isSet():
print u'C:太好了'
break
else:
print '做其他事情去了……'
time.sleep(0.08)
event = threading.Event()
p = threading.Thread(target=shengchang)
c = threading.Thread(target=xiaofei)
p.start()
c.start()
'''
#-------------------IP换算----------------------
'''
def ch1(num):
s = []
for i in range(4):
s.append(str(num%256))
print s
num /= 256
return '.'.join(s[::-1])
print ch1(123456789)
#用lambda的方式,整数toIP 地址 一行代码搞定
ch2 = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)])
print ch2(123456789)
#用lambda的方式,IP地址转换到整数
ch3 = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])])
print ch3('7.91.205.21')
'''
#-------------------IP敬意计算----------------------
import os
'''
def getip(ip, count):
count = int(count)
ip2 = int(ip.split('.')[-2])
ip1 = int(ip.split('.')[-1])
ip_before = '%s.%s' % (ip.split('.')[0], ip.split('.')[1])
for i in range(0,count,4):
new_ip1 = ip1 + i
if 11 <= new_ip1 <= 254:
print '%s.%s.%s' % (ip_before, str(ip2), str(new_ip1))
else:
new_ip2 = ip2 + int(new_ip1/254)
new_ip1 = new_ip1%254 + 0
print '%s.%s.%s' % (ip_before, str(new_ip2), str(new_ip1))
if __name__ == '__main__':
getip('10.0.1.0', 1000)
'''
'''
def getip(ip, count,step):
count = int(count)
ip1 = int(ip.split('.')[-1])
ip2 = int(ip.split('.')[-2])
ip3 = int(ip.split('.')[-3])
ip4 = int(ip.split('.')[-4])
ip_before = '%s.%s' % (ip.split('.')[0], ip.split('.')[1])
for i in range(0,count,step):
new_ip1 = ip1 + i
#print '%s.%s.%s' % (ip_before, str(ip2), str(new_ip1))
if new_ip1 <= 255:
pass
print '%s.%s.%s' % (ip_before, str(ip2), str(new_ip1))
else :
new_ip2 = ip2 + int(new_ip1/256)
if new_ip2 <= 255:
new_ip1 = new_ip1%256
print '%s.%s.%s' % (ip_before, str(new_ip2), str(new_ip1))
else:
new_ip3 = ip3 + int(new_ip2/256)
new_ip2 = ip1 + int(new_ip1/256)
new_ip1 = new_ip1%256
#print 'ip1------------:',new_ip1
new_ip2 = 0
if new_ip1 >= (256/step-1)*step:
new_ip2 += 1
new_ip1 = new_ip1%256
#print 'ip2-----:',new_ip2
print '%s.%s.%s.%s' % (str(ip4),str(new_ip3), str(new_ip2), str(new_ip1))
if __name__ == '__main__':
getip('10.0.255.192',830,32)
'''
#---------------------pexpect 交互连接------------------------
'''
#!/usr/bin/env python
#coding=utf-8
import pexpect
import time,re
import pymysql
loginprompt = '#'
def get(login_ip):
login = 'telnet %s' % login_ip
tn = pexpect.spawn(login,timeout = 300)
#tn.expect('Username:')
flag = tn.expect(["login","Username:", "(?i)Unknown host", pexpect.EOF, pexpect.TIMEOUT])
username = 'opsinfo'
password = 'pwdops'
if flag == 0 or flag == 1:
tn.sendline(username)
tn.expect('Password:')
tn.sendline(password)
tn.expect(r'[#>]')
print tn.before
#交互开始
tn.interact()
print 'Left interactv mode'
else:
print 'error'
if __name__ == '__main__':
login_ip = raw_input('IP: ')
get(login_ip)
'''
#---------------------ping 主机------------------------
'''
#!/usr/bin/env python
import multiprocessing
import subprocess
import time
start_time = time.time()
host_list = ['192.168.100.254','1.1.1.1','192.168.100.253','114.28.127.2','114.28.127.72','114.28.127.70','114.28.127.12','114.28.127.56','114.28.127.102']
if len(host_list) > 30:
process_number = 30
else:
process_number = len(host_list)
def ping_host(ipaddr):
if subprocess.call('ping -c5 -W 1 %s > /dev/null' % ipaddr, shell=True) == 0:
#if subprocess.call('ping -c1 -W 1 %s ' % ipaddr, shell=True) == 0:
print '%s is OK' % ipaddr
else:
print '%s is DOWN' % ipaddr
pool = multiprocessing.Pool(processes=10)
for ip in host_list:
pool.apply_async(ping_host,(ip,))
#pool.map(ping_host,host_list)
pool.close()
pool.join()
end_time = time.time()
print 'It is take %.2f seconds'%(start_time-end_time)
'''
#---------------------从文件中找出IP地址------------------------
'''
import re
f = file('d:\ip.txt','rb')
set1 = set()
for line in f.xreadlines():
try:
ip = ''.join(re.findall('(?:\d+\.){3}\d{1,3}', line))
#print ip
set1.add(ip)
except:
pass
f.close()
set1 = sorted(set1)
#print set1
for i in set1:
print i
'''
#---------------------用Pexpect登录设备并测试Ping-----------------------
'''
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import pexpect
import re
import time
问题:
1.迭代查询和Ping包,第二次总是看不到查询的结果,导致搜索错误,在Python中直接测试正常
2.另一个问题:通过expect如果PIng不到,是否有返回结果,好像看不到
f = file('/smb/python_s8/day8/ip.txt','rb')
username = 'pingtest'
password = 'pwdtest'
tn = pexpect.spawn('telnet 219-mr01')
#index = tn.expect(["Username:",pexpect.EOF, pexpect.TIMEOUT])
try:
#if index == 0:
tn.expect('Username:')
tn.sendline(username)
tn.expect('Password:')
tn.sendline(password)
print 'auth is ok'
x= 1
for line in f.xreadlines():
#print line
tn.expect('#')
#print 'is this running?'
tn.sendline('sh ip vrf interface | inc %s' % line)
tn.expect('#')
result = tn.before
tn.expect('#')
# print len(result)
print '-------------------this is %d result:---------------\n%s\n'%(x,result)
ip = ''.join(re.findall('(?:\d+\.){3}\d{1,3}', result))
vrf = ''.join(re.findall('(\w{3,5}\d{3,6}\w+)',result))
print 'ip: %s , vrf: %s' %(ip,vrf)
#这里更改目标IP地址
ip1= ip.split('.') #分割IP
if ip1[0] == '114':
ip1[3] =str(int(ip.split('.')[-1])+1) #替换最后一个IP数字
else:
ip1[3] =str(int(ip.split('.')[-1])-1) #替换最后一个IP数字
targetIP ='.'.join(ip1)
#组合命令
cmd = 'ping vrf %s %s re 2'%(vrf,targetIP)
print cmd
try:
tn.sendline(cmd)
except:
print 'error'
time.sleep(10)
tn.expect('#')
#tn.expect('#')
result1 = tn.before
print result1
#tn.sendline('\r\r\r')
x += 1
tn.sendline('exit')
# elif index == 1:
# print 'pexpect.EOF'
# else:
# print 'pexpect.TIMEOUT'
except Exception,e:
print e
'''
#---------------------Jump跳板机----------------------
#!/usr/bin/python
# # coding:utf-8
# import sys
# import time
# import re
# import pexpect
# import os
# import struct
# import fcntl
# import termios
# import signal
# import MySQLdb
#
#
# def sigwinch_passthrough (sig, data):
# winsize = getwinsize()
# global child
# child.setwinsize(winsize[0],winsize[1])
#
# def getwinsize():
# if 'TIOCGWINSZ' in dir(termios):
# TIOCGWINSZ = termios.TIOCGWINSZ
# else:
# TIOCGWINSZ = 1074295912L # Assume
# s = struct.pack('HHHH', 0, 0, 0, 0)
# x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
# return struct.unpack('HHHH', x)[0:2]
#
# def getServersList():
# sqlStr = ''' select * from sys_info '''
# cursor.execute(sqlStr)
# rows = cursor.fetchall()
# strList = ''
# for index, row in enumerate(rows):
# strList += 'Hostname:%s , IP:\033[1;34;40m%s\033[0m \n' % (row[0],row[1])
# return strList
#
# def sshLogin(choice):
# reip = re.compile(r'(?
# if len ( reip.findall(choice) ) == 0:
# print '\033[1;31;40mIP Error you entered.Please Enter again.\033[0m'
# return
# host = reip.findall(choice)[0]
# sqlStr = ''' select count(*) from sys_info where ip='%s' ''' % host
# cursor.execute(sqlStr)
# rows = cursor.fetchall()
# if rows[0][0] == 0:
# print '\033[1;31;40mThe IP you entered is not in the list.\033[0m'
# return
# sqlStr = ''' select * from sys_info where ip='%s' ''' % host
# cursor.execute(sqlStr)
# rows = cursor.fetchall()
# username =rows[0][2]
# passwd =rows[0][3]
# print 'ssh ' + username + '@' + host + ' ...'
# global child
# child = pexpect.spawn('ssh %s@%s' % (username,host))
# #child = pxssh.pxssh()
# child.logfile = fout
# #child.logfile = sys.stdout
# #child.logfile_send = sys.stdout
# signal.signal(signal.SIGWINCH, sigwinch_passthrough)
#
# winsize = getwinsize();
# child.setwinsize(winsize[0], winsize[1])
# flag = child.expect(['continue', 'password', pexpect.EOF, pexpect.TIMEOUT])
# #child.login (host, username, passwd, original_prompt='[$#>]')
# #child.prompt()
# #print flag
# if flag == 0:
# child.sendline('yes')
# child.expect('.*password:.*')
# child.sendline(passwd)
# elif flag == 1:
# child.sendline(passwd)
# child.interact()
# pass
#
# if __name__ == '__main__':
# DBHOST='127.0.0.1'
# DBNAME='jump'
# DBUSER = 'root'
# DBPWD = 'db03dUNG'
# FILENAME = '/data/build/command_jump.log'
# WELCOME = '''\033[1;34;40m### Welcome use JumpServer to Login. ### \033[0m '''
# CHOICE = """1. Type \033[1;34;40mIP ADDRESS\033[0m To Login.
# 2. Type \033[1;34;40mP/p\033[0m To Print The Servers You Available.
# 3. Type \033[1;34;40mQ/q\033[0m To Quit.
# \033[1;34;40mOpt or IP>:\033[0m """
# try:
# conn = MySQLdb.connect(host='%s' % DBHOST ,user='%s' % DBUSER , passwd='%s' % DBPWD , db='%s' % DBNAME , charset='utf8')
# except Exception, e:
# print e
# sys.exit()
# cursor = conn.cursor()
# fout = open (FILENAME , "ab")
# print WELCOME
# while True:
# choice = raw_input( CHOICE )
# if cmp(choice,"P") == 0 or cmp(choice,"p") == 0 :
# print getServersList()
# elif cmp(choice,"Q") == 0 or cmp(choice,"q") == 0:
# print 'Exit.'
# break
# else:
# sshLogin(choice)
#
# cursor.close()
# conn.close()
# fout.close()
#
# [root@jump1 build]#