1. 程式人生 > >Python2之windows輸出亂碼及倒計時程式碼處理

Python2之windows輸出亂碼及倒計時程式碼處理

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import time
import platform
# 亂碼處理
sys_encoding = sys.getfilesystemencoding()
def printcn(msg):
    print(msg.decode('utf-8').encode(sys_encoding))

def partition(str, sep):
    return [str.split(sep)[0], sep, sep.join(str.split(sep)[1:])]


def rpartition(str, sep):
    return [sep.join(str.split(sep)[:-1]), sep, str.split(sep)[-1]]


def getLocalips(system_type):
    localips = set()
    if system_type == 'Windows':
        cmd_getip = "ipconfig"
    elif system_type == 'Linux':
        cmd_getip = "ip a"
    localipline = os.popen(cmd_getip).readlines()
    if system_type == 'Windows':
        localipline = [partition(partition(x, ':')[2], '(')[0].strip() for x in localipline if
                       'IPv6' in x or 'IPv4' in x]
    elif system_type == 'Linux':
        localipline = [x.split()[1].split('/')[0] for x in localipline if ' inet' in x]
    for ip in localipline:
        localips.add(ip.rstrip('\n'))
    localips.add('0.0.0.0')
    localips.add('::')
    temp = set()
    for ip in localips:
        if '.' in ip:
            temp.add('::ffff:' + ip)
    localips = localips | temp
    return localips


listSrvFor = set()
listAcc = set()
LISTENs = {}
GlobalListenPorts = set()

mydir = os.path.dirname(os.path.realpath(__file__))


# print(mydir)


def main():
    """
    程式入口
    :return:
    """
    system_type = platform.system()
    # print(system_type)
    if system_type == 'Windows':
        cmd_netstat = "netstat -ano"
        local_position = 1
        remote_position = 2
        status_position = 3
        pid_position = 4
    elif system_type == 'Linux':
        cmd_netstat = "netstat -anp|grep -v ' STREAM \| DGRAM '|grep :"
        local_position = 3
        remote_position = 4
        status_position = 5
        pid_position = 6
    else:
        print(u'不支援此作業系統')
        exit()

    localips = getLocalips(system_type)
    # print(localips)

    lines = os.popen(cmd_netstat).readlines()
    if system_type == 'Windows':
        lines = [x for x in lines if x.startswith('  TCP')]
    elif system_type == 'Linux':
        lines = [x for x in lines if x.startswith('tcp')]

    for line in lines:
        info = line.split()
        if info[status_position].startswith('LISTEN'):
            LISTENs[info[local_position]] = info[pid_position]
            if rpartition(info[local_position], ':')[0] in ('0.0.0.0', '::'):
                GlobalListenPorts.add(rpartition(info[local_position], ':')[2])

    for line in lines:
        info = line.split()
        if not info[status_position].startswith('LISTEN'):
            ip1 = rpartition(info[local_position], ':')[0]
            ip2 = rpartition(info[remote_position], ':')[0]
            if (ip1 not in localips or ip2 not in localips) and ip1 != ip2:
                if info[local_position] in LISTENs or (
                        ip1 in localips and rpartition(info[local_position], ':')[2] in GlobalListenPorts):
                    listSrvFor.add(info[local_position] + '<-' + ip2)
                elif info[remote_position] in LISTENs or (
                        ip2 in localips and rpartition(info[remote_position], ':')[2] in GlobalListenPorts):
                    listSrvFor.add(info[remote_position] + '<-' + ip1)
                elif ip1 in localips:
                    listAcc.add(info[remote_position])  # +'<-'+info[3])
                    # listAcc.add('a++'+line)
                else:
                    listAcc.add(info[local_position])  # +'<-'+info[4])
                    # listAcc.add('b++'+line+str(localips)+str(GlobalListenPorts))

    # print(LISTENs)

    LISTENs_file = os.path.join(mydir, 'LISTENs.txt')
    if os.path.exists(LISTENs_file):
        Ftxt = open(LISTENs_file, 'r')
        old = Ftxt.readlines()
        Ftxt.close()
    else:
        old = []
    old = set([x.rstrip('\n') for x in old])
    new = set([x + ' -> ' + LISTENs[x] for x in LISTENs])
    if not new.issubset(old):
        Ftxt = open(LISTENs_file, 'w')
        LISTENs2 = new | old
        Ftxt.write('\n'.join(sorted(list(LISTENs2))))
        Ftxt.close()
        # print('writefile:LISTENs.txt')

    SrvFor_file = os.path.join(mydir, 'SrvFor.txt')
    if os.path.exists(SrvFor_file):
        Ftxt = open(SrvFor_file, 'r')
        old = Ftxt.readlines()
        Ftxt.close()
    else:
        old = []
    old = set([x.rstrip('\n') for x in old])
    new = listSrvFor
    if not new.issubset(old):
        listSrvFor2 = new | old
        Ftxt = open(SrvFor_file, 'w')
        Ftxt.write('\n'.join(sorted(list(listSrvFor2))))
        Ftxt.close()
        # print('writefile:SrvFor.txt')

    Access_file = os.path.join(mydir, 'Access.txt')
    if os.path.exists(Access_file):
        Ftxt = open(Access_file, 'r')
        old = Ftxt.readlines()
        Ftxt.close()
    else:
        old = []
    old = set([x.rstrip('\n') for x in old])
    new = listAcc
    if not new.issubset(old):
        listAcc2 = new | old
        Ftxt = open(Access_file, 'w')
        Ftxt.write('\n'.join(sorted(list(listAcc2))))
        Ftxt.close()
        # print('writefile:Access.txt')


if __name__ == '__main__':
	# 亂碼處理
    reload(sys)
    sys.setdefaultencoding("utf-8")
    while True:
        print(time.strftime('%Y-%m-%d %H:%M:%S ', time.localtime(time.time())))
        main()
        printcn('\033[36m%s\033[0m' % '檔案處理成功,請檢視相應的檔案!')
        printcn('\033[35m%s\033[0m' % '延時30秒,等待下次處理結果......')
        # 倒計時
        for x in xrange(30, 1, -1):
            sys.stdout.write(str(x)+' ')
            time.sleep(1)
            os.system('cls')