python中summary_python summary_study.py

#!/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__':

print

-------------------------------------------------

请选择你需要的功能:

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]#

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/304668.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

NLog整合Exceptionless

前言在实际的.Net Core相关项目开发中&#xff0c;很多人都会把NLog作为日志框架的首选&#xff0c;主要是源于它的强大和它的扩展性。同时很多时候我们需要集中式的采集日志&#xff0c;这时候仅仅使用NLog是不够的&#xff0c;NLog主要是负责代码中日志的落地&#xff0c;也就…

40个只有程序员才看得懂的段子

1. 一程序员去面试&#xff0c;面试官问&#xff1a;“你毕业才两年&#xff0c;这三年工作经验是怎么来的&#xff1f;&#xff01;”程序员答&#xff1a;“加班。”2. 某程序员对书法十分感兴趣&#xff0c;退休后决定在这方面有所建树。于是花重金购买了上等的文房四宝。一…

bra型手机链

左看看&#xff0c;右瞧瞧&#xff0c;真不敢相信这个居然是手机链&#xff1f;带上它出门&#xff0c;回头率一定很高哦&#xff01;就是有点贵&#xff0c;70元&#xff01;转载于:https://blog.51cto.com/laizhngn5376/180850

MySQL8的inodb参数设置_MySQL8.0自适应参数innodb_dedicated_server

MySQL8.0有了一个新参数又叫自适应参数 innodb_dedicated_server将innodb_dedicated_server开启的时候&#xff0c;它可以自动的调整下面这四个参数的值&#xff1a;innodb_buffer_pool_size 总内存大小innodb_log_file_size redo文件大小innodb_log_files_in_group redo文件数…

让 gRPC 提供 REST 服务

让 gRPC 提供 REST 服务IntrogRPC 是一个高性能、开源和通用的 RPC 框架&#xff0c;面向移动和 HTTP/2 设计。gRPC 基于 HTTP/2 标准设计&#xff0c;带来诸如双向流、流控、头部压缩、单 TCP 连接上的多复用请求等特。这些特性使得其在移动设备上表现更好&#xff0c;更省电…

python提取cad坐标到excel_使用python来操作autocad,并且将坐标点转换成cad可见对象...

由于工作需要&#xff0c;在项目中遇到一个棘手的问题&#xff0c;如何将(mssql)数据库中的BLOB文件转成cad可见图形(可能每个项目需求不一样&#xff0c;解决方式不同)第一步 . 需要转换的图形类型第二步 . 那我们先查询这个字段第三步 试试将这个写入一个文本中 看看是那种图…

10张图看懂瞎忙和高效的区别

时间是最公平的&#xff0c;每个人一天都是24小时&#xff0c;一年都是365天。但是&#xff0c;不同的人的产出却是天差地别。人和人的差距为什么这么大&#xff1f;而且这种差距&#xff0c;并不是家庭背景、权利财富或天赋带来的&#xff0c;仅仅是我们对时间的掌控。正好看到…

pc模式 华为mate30_华为mate30与电脑连不上怎么回事

大家好&#xff0c;我是时间财富网智能客服时间君&#xff0c;上述问题将由我为大家进行解答。系统版本为EMUI 10.1&#xff0c;华为mate30与电脑连不上的原因&#xff1a;1、可能是USB线连接不正常。建议更换数据线试试。2、确认电脑上的手机USB 驱动已经安装成功&#xff0c;…

ASP.NET Core 中的配置

背景ASP.NET Core 提供了一个灵活可扩展,基于键值的配置系统. 但是配置系统独立于ASP.NET Core是Microsoft.Extensions 类库的部分. 它可以用于任何类型的应用程序。1、以键-值对的形式读取配置appsettings.json 文件&#xff1a;{"Position": {"Title": &…

Canvas的save和restore

在创建新的控件或修改现有的控件时&#xff0c;我们都会涉及到重写控件或View的onDraw方法。 onDraw方法会传入一个Canvas对象&#xff0c;它是你用来绘制控件视觉界面的画布。 在onDraw方法里&#xff0c;我们经常会看到调用save和restore方法&#xff0c;它们到底是干什么用的…

vs code python 插件_工具篇-vscode效率提升插件

工欲善其事必先利其器&#xff0c;开发前先把所以提升效率的利器搭好会让今后慢慢的编程长路舒服很多&#xff0c;我本来一直用pycharm&#xff0c;后来发现vscode貌似确实会好很多。。。就慢慢转过来了&#xff0c;下面介绍一些我在机器学习编程时经常会用到的一些插件。1. au…

鉴别一个人是否 js 入门的标准竟然是?!

不知不觉跳入前端「大坑」也已经有大半年了&#xff0c;学到了很多知识。为了让知识更好地沉淀&#xff0c;我打算写一系列的知识总结&#xff0c;希望能在回顾知识的同时也能帮到别的同学。忘记在哪里看到过&#xff0c;有人说鉴别一个人是否 js 入门的标准就是看他有没有理解…

面向对象编程设计模式--简单工厂模式讲解(历史上最简单明白的例子)

工作之余&#xff0c;在看资料过程中发现一个极易理解的简单工厂模式的例子&#xff0c;自己亲自试练一番,感觉对这个设计模式不熟悉的朋友&#xff0c;一看马上就知道是什么回事了。 简单工厂模式根据提供给它的数据&#xff0c;返回几个可能类中的一个类的实例。通常它返的类…

.NET 6 Preview 1 开箱,带你体验新版本

最近 .NET 6 Preview 1 发布了&#xff0c;.NET 统一是此版本的核心。大家可以读一下原文博客&#xff1a;https://devblogs.microsoft.com/dotnet/announcing-net-6-preview-1/.NET 6.0 SDK 和 Runtime 下载地址&#xff1a;https://dotnet.microsoft.com/download/dotnet/6.0…

redis 清空缓存_「镜头回放」简直了!spring中清除redis缓存导致应用挂死

异常场景springWeb应用一直运行正常&#xff0c;同事最近反应&#xff0c;每次版本更新完毕&#xff0c;刷新缓存&#xff0c;就会导致应用挂死。只有重启redis应用才恢复正常。项目概况springWeb项目&#xff0c;常用配置表做了redis缓存&#xff0c;配置表中只有少量数据&…

25岁社招进阿里,从电商到有赞新零售,他仅1年就打开了马云一直想做的新领域!

最近关于「新零售」的声音此起彼伏&#xff1a;阿里巨资收购高鑫零售&#xff0c;腾讯确认入股永辉超市……自2016年10月马云第一次提出了「新零售」概念之后&#xff0c;各巨头跑马圈地&#xff0c;线下成为了必争之地&#xff0c;新零售的蓝海才刚刚打开。而李星&#xff0c;…

优美的测试代码 - 行为驱动开发(BDD)

可理解的代码非常重要&#xff0c;测试代码也是如此。在我看来&#xff0c;优秀的测试代码&#xff0c;必须做到一个重要的事情就是保持测试逻辑的清晰。一个完整的测试案例通常包括三个部分&#xff1a;1. SetUp2. Exercise3. Verifiy4. TearDown一 个测试案例如果能清晰的区分…

C#连接MySQL数据库实例

项目目的&#xff1a;连接mysql查询数据并将数据显示到界面的datagridview里面.Step1:添加动态链接库文件Visual Studio,在 项目(右键)-管理NuGet程序包(N) 然后在浏览里面搜索MySql.Data并进行安装。Step2&#xff1a;using所需要的库using MySql.Data.MySqlClient;step3&…

java字符串比大小_Java字符串比较(3种方法)

字符串比较是常见的操作&#xff0c;包括比较相等、比较大小、比较前缀和后缀串等。在 Java 中&#xff0c;比较字符串的常用方法有 3 个&#xff1a;equals() 方法、equalsIgnoreCase() 方法、 compareTo() 方法。下面详细介绍这 3 个方法的使用。equals() 方法equals() 方法将…

链接服务器 慢_redis服务器cpu100%的原因和解决方案

首先引起cpu100%可能的几大原因&#xff1a;1.redis连接数过高2.数据持久化导致的阻塞3.主从存在频繁全量同步4.value值过大5.redis慢查询为了模拟redis服务器cpu100%&#xff0c;临时买了一台阿里云ecs&#xff0c;并把那天清空前的redis备份还原到服务器上。下面我们按照顺序…