zoukankan      html  css  js  c++  java
  • 小脚本

    1.找出某目录下所有以‘.log’结尾的文件并删除

    1 import os
    2 print(os.getcwd())
    3 os.chdir(r'文件所在目录')
    4 li = os.listdir()#列出该目录下的所有文件
    5 for i in li:
    6     if i.endswith('.log'):  #找出所有以.log结尾的文件并删除
    7         os.remove(i)

     2.利用paramiko批量远程登录服务器执行命令,并返回结果

     1 import  commands
     2 import subprocess
     3 import paramiko
     4 import time
     5 host_lists=(
     6 ('192.168.1.12'),
     7 ('192.168.1.240'),
     8 ('172.168.96.3'),
     9 ('192.168.1.12'),
    10 ('172.168.96.3'),
    11 ('192.68.23.25'),
    12 ('10.236.53.69'),
    13 ('11.23.36.33'),
    14 )
    15 
    16 
    17 def getServerInfo(host,user,password,services):
    18     conn=paramiko.SSHClient()
    19     conn.load_system_host_keys()
    20     conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    21     conn.connect(hostname=host,port=22,username=user,password=password,allow_agent=False,look_for_keys=False)
    22     stdin,stdout,stderr=conn.exec_command("ps aux|awk '{print $3,$4,$5,$6,$11}'|grep %s" % services,timeout=5)#要执行的命令
    23     info=stdout.read()  # 在python3中,获取的info值是字节型(b'dsfdfffd'),要decode一下
    info = info.decode('utf-8')
     conn.close()
    24 return info 25 def ping_test(host): 26 p = commands.getoutput("ping "+host+" -w 1|wc -l") #指定ping一秒 27 if p =='6': #如果能ping通 28 info=getServerInfo(host,'root','111111','pick') 29 info_list=info.split() 30 print "%s %s %s %s %s %s "%(host,info_list[0],info_list[1],info_list[2],info_list[3],info_list[4]), 31 with open("yes.log","a+") as f: 32 f.write(host+' ') 33 elif p == '5': #如果不能ping通 34 print "%s NO NO NO NO NO "% (host), 35 with open("no.log","a+") as f_no: 36 f_no.write(host+' ') 37 def out_info(): 38 now1 = time.time() 39 ping_test(host) 40 now2 = time.time() 41 now3 = now2 - now1 42 print " ",now3 43 if __name__ == '__main__': 44 print"ip %CPU %MEM VSZ RSS services time_use(s)" 45 46 for host in host_lists: 47 try: 48 out_info() 49 except: 50 print host," NO_ssh" 51 with open("no_ssh.log","a+") as f_except: 52 f_except.write(host+' ')

     3.paramiko/client.py

    第220行设置网络不通超时时间

    4.设置输出颜色

    格式:033[显示方式;前景色;背景色m
     
    说明:
    前景色            背景色           颜色
    ---------------------------------------
    30                40              黑色
    31                41              红色
    32                42              绿色
    33                43              黃色
    34                44              蓝色
    35                45              紫红色
    36                46              青蓝色
    37                47              白色
    显示方式           意义
    -------------------------
    0                终端默认设置
    1                高亮显示
    4                使用下划线
    5                闪烁
    7                反白显示
    8                不可见
     
    例子:
    033[1;31;40m    <!--1-高亮显示 31-前景色红色  40-背景色黑色-->
    033[0m          <!--采用终端默认设置,即取消颜色设置-->   
    复制代码
    • 备注:
      • 33[1;31;40m: 代表接下来输出内容为:高亮显示,前景色为红色,背景色被黑色。
      • 33[0m:代表接下来的输入内容为终端默认设置,也就是取消之前的颜色设置,如果没有这个,接下来的输出,都是上面的设置。
    • 例子:
    password = raw_input('请输入用户密码,如果不设置,33[5;33;40m请回车!33[0m。默认密码为: NewPassWord2016)')
      • 我的设置是,闪烁、前景色为黄色,背景色为黑色。输出的效果是:”请回车“  这三个字一直在闪烁,且字体为黄色,背景色为黑色。

    5.获取当前局域网内的所有在用ip

     1 ##python 2.7
     2 import platform
     3 import sys
     4 import os
     5 import time
     6 import thread
     7 
     8 
     9 def get_os():
    10     os = platform.system()
    11     if os == "Windows":
    12         return "n"
    13     else:
    14         return "c"
    15 
    16 
    17 def ping_ip(ip_str):
    18     cmd = ["ping", "-{op}".format(op=get_os()),"1", ip_str]
    19     output = os.popen(" ".join(cmd)).readlines()
    20 
    21     flag = False
    22     for line in list(output):
    23         if not line:
    24             continue
    25         if str(line).upper().find("TTL") >= 0:
    26             flag = True
    27             break
    28     if flag:
    29         print "ip: %s is useing ***" % ip_str
    30 
    31 
    32 def find_ip(ip_prefix):
    33     for i in range(1, 256):
    34         ip = '%s.%s' % (ip_prefix, i)
    35         thread.start_new_thread(ping_ip, (ip,))
    36         time.sleep(0.3)
    37 
    38 
    39 if __name__ == "__main__":
    40     commandargs = raw_input( "Enter start IP  [For example:192.168.1.1] >>>")
    41     print "start time %s" % time.ctime()
    42     commandargs = str(commandargs)
    43     args = "".join(commandargs)
    44     ip_prefix = '.'.join(args.split('.')[:-1])
    45     find_ip(ip_prefix)
    46     print "end time %s" % time.ctime()

     6.根据ip地址获取当前位置信息(调用百度地图接口)

    基于python3.5

    from urllib import request
    import gevent,time
    import json
    from gevent import monkey
    monkey.patch_all() #把当前程序的所有的io操作单独的做上标记,这样gevent就可以识别到io操作了
    
    def f(url):
        print('GET: %s' % url)
        resp = request.urlopen(url)
        data = resp.read().decode()
        with open('ip.txt','w') as f:
            f.write(data)
        with open("ip.txt","r") as f:
            for i in f:        #注意,json反序列化的时候要迭代才可以,否则报错
                c = json.loads(i)
            print(type(c),c)
            print(c["address"])
        print('%d bytes received from %s.' % (len(data), url))
    
    async_time_start = time.time()
    gevent.joinall([
    #     gevent.spawn(f, 'https://www.python.org/'),
    #     gevent.spawn(f, 'https://www.yahoo.com/'),
    #     gevent.spawn(f, 'https://github.com/'),
          gevent.spawn(f, 'http://api.map.baidu.com/location/ip?ak=NKrVZ3qLBjSG47KKMjIsfNW3CSwrp4GT&coor=bd09ll',)
    ])
    print("异步cost",time.time() - async_time_start)
    
    输出:
    GET: http://api.map.baidu.com/location/ip?ak=NKrVZ3qLBjSG47KKMjIsfNW3CSwrp4GT&coor=bd09ll
    <class 'dict'> {'address': 'CN|山东|济宁|None|UNICOM|0|0', 'content': {'point': {'x': '116.60079762', 'y': '35.40212166'}, 'address': '山东省济宁市', 'address_detail': {'district': '', 'street_number': '', 'province': '山东省', 'city_code': 286, 'city': '济宁市', 'street': ''}}, 'status': 0}
    CN|山东|济宁|None|UNICOM|0|0
    317 bytes received from http://api.map.baidu.com/location/ip?ak=NKrVZ3qLBjSG47KKMjIsfNW3CSwrp4GT&coor=bd09ll.
    异步cost 0.062041282653808594

    基于python2.7

     1 # encoding=utf8
     2 
     3 import json
     4 import urllib2
     5 import httplib
     6 #调用百度地图接口
     7 url = 'http://api.map.baidu.com/location/ip?ak=NKrVZ3qLBjSG47KKMjIsfNW3CSwrp4GT&coor=bd09ll'
     8 temp = urllib2.urlopen(url)
     9 hjson = json.loads(temp.read())
    10 #print hjson
    11 province = hjson['content']['address_detail']['province']
    12 city = hjson['content']['address_detail']['city']
    13 city_code = hjson['content']['address_detail']['city_code']
    14 address = hjson['content']['address']
    15 point = hjson['content']['point']
    16 aa = hjson['address']
    17 print "城市代码:",city_code
    18 print "地址:",address
    19 print "纬度:",point['y']
    20 print '经度:',point['x']
    21 print "详细(包含地址及运营商信息):",aa

     7.进度条

     1 #!usr/bin/env/python
     2 # -*- coding:utf-8 -*-
     3 # from  wangteng
     4 import time
     5 import sys
     6 for i in range(101):
     7     sys.stdout.write('
    ')
     8     sys.stdout.write("%s%% |%s" %(int(i%101), int(i%101)*'#'))
     9     sys.stdout.flush()
    10     time.sleep(0.5)
    11 
    12 sys.stdout.write('
    ')
     1 #!usr/bin/env/python
     2 # -*- coding:utf-8 -*-
     3 # from  wangteng
     4 import time
     5 import sys
     6 for i in range(101):
     7     sys.stdout.write('
    ')
     8     sys.stdout.write("%s%% |%s" %(int(i%101), int(i%101)*'#'))
     9     sys.stdout.flush()
    10     time.sleep(0.5)
    11 
    12 sys.stdout.write('
    ')

    可以根据以下代码修改,将分子分母都修改为变量
    zi = 67
    fu = 103
    a = zi/fu*100
    a = int(a)
    print(a*'#')
    a = str(a)
    print(a[:5],'%')

     8.mysql表插入数据时自动添加插入时间,只需要在原表上再加一个字段即可TIMESTAMP

        ALTER TABLE t2 ADD nowtime TIMESTAMP default CURRENT_TIMESTAMP;

     9.html每5秒自动刷新页面

    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <META HTTP-EQUIV="Refresh" CONTENT="5">
    </head>

    10.html修改时间格式

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <META HTTP-EQUIV="Refresh" CONTENT="5">
    </head>
    <body>
    主要是script代码
    <script>
    function date2str(x,y) {
        var z = {M:x.getMonth()+1,d:x.getDate(),h:x.getHours(),m:x.getMinutes(),s:x.getSeconds()};
        y = y.replace(/(M+|d+|h+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-2)});
        return y.replace(/(y+)/g,function(v) {return x.getFullYear().toString().slice(-v.length)});
    }
    var d = new Date('Mon Feb 06 2017 16:21:44');自定义一个时间
    alert(date2str(d,"yyyy-MM-dd hh:mm:ss"));
    alert(date2str(d,"yyyy-M-d h:m:s"));
    </script>
    </body>
    </html>
  • 相关阅读:
    Unity 之 中文乱码
    fork调用的底层实现
    Linux错误代码含义
    VMware 获取该虚拟机的所有权失败
    Qt ------ QAction
    C++ ------ const迭代器 和 const_iterator的区别
    IAR ------- 在线调试技巧
    STM32 ------ HardFault_Hander 中断函数
    从一张表中复制数据到另一张表中
    分布式任务调度平台xxl-job
  • 原文地址:https://www.cnblogs.com/wt11/p/5852191.html
Copyright © 2011-2022 走看看