1. 程式人生 > >幾個小功能程式碼!有檢測tcp伺服器的

幾個小功能程式碼!有檢測tcp伺服器的

有需要可以看看,閒著無聊寫的

import os, sys,  pickle

import threading
import pexpect
import re
import logging
import socket

linkServerIpList    = []
linkServerNameList  = []
portList            = []

#獲取所有的伺服器IP和名字列表
def getServerIpByReadFiles (targetPath):
    serverIpList   = []
    serverNameList = []
    if os.path.isfile(targetPath):
        with open(targetPath, 'r+') as fd:
            while True:
                read_info = fd.readline()
                print(read_info)
                if len(read_info) > 0:
                    serverIp    = re.search(r"(\d*?)\.(\d*?)\.(\d*?)\.(\d+)", read_info).group().strip()
                    serverName  = re.search(r'[a-z]{5,7}', read_info).group().strip()

                    serverIpList.append(serverIp)                
                    serverNameList.append(serverName)

                else:
                    print("讀取伺服器IP和名字完畢!")
                    break

    return  (serverIpList, serverNameList)

#將所有伺服器IP和名字寫入檔案
def ip_Name_File(serverIpList, serverNameList):
    print(serverIpList)
    print(len(serverIpList))
    
    openfile = open('.iplist.temp', 'w')
    for index in range(len(serverIpList)):
        openfile.write(serverIpList[index] + ':' + serverNameList[index] + '\n')

    print("檔案寫入成功!")
    openfile.close()

#獲取tcp伺服器的IP列表
def commonTcpProbeServer (serverIpList, serverNameList, port):
    clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #clientSocket.settimeout(2)
    clientSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    clientSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    num = 0

    for index, serverIp in  enumerate(serverIpList):
        try:
            print('Check: ' + serverIp + ' : ' + str(port))
            
            clientSocket.connect((serverIp, port))
            #if clientSocket.connect_ex((serverIp, port)) != 0:
            #    print(r)
            #    continue

            clientSocket.send("hello".encode("gb2312"))
            print('send  success')

            recvdata = clientSocket.recv(2048)
            if len(recvdata):
                print("recvData from server ip: %s :架構:%s" % (serverIp, recvdata.decode("gb2312")))
            else:
                print('recv data error')
                continue

            if len(linkServerIpList) > 0:
                for i in  range(len(linkServerIpList)):
                    if serverIp == linkServerIpList[i]:
                        continue
                    else:
                        num += 1
                        if num == len(linkServerIpList):
                            linkServerIpList.append(serverIp)
                            linkServerNameList.append(serverNameList[index])
            else:
                linkServerIpList.append(serverIp)
                linkServerNameList.append(serverNameList[index])

            tmpPort = recvdata.decode("gb2312") + ':' + serverIp + ':' + str(port)
            portList.append(tmpPort)
            clientSocket.close()
            break

        except Exception as e:
            print(e) 
            continue

#將當前可TCP連線的伺服器IP寫入相應文件
def writeTCPServerLog():
    print("TCP Server can connect include %s" %linkServerIpList)
    with open('.tcpserver.temp', 'w') as openfd:
        for index in range(len(linkServerIpList)):
            openfd.write("<option>" + linkServerIpList[index] + "</option>")

def writeSystemLog():
    with open('.sys.temp', 'w') as fd:
        for index in range(len(portList)):
            fd.write('<option value="0">' + portList[index] + '</option>' + '\n')

#遍歷所有可以tcp連線的server
def viewLinkServerIpList():
    flags = False
    
    if len(linkServerIpList):
        for index, serverIp in enumerate(linkServerIpList):
            print("Server: %s can be connected!" %serverIp)
        for attr in portList:
            print('The port can use:' + str(attr))

        return len(linkServerIpList)
    else:
        print("No server can be connected!")
        return flags

if __name__ == "__main__":
    '''
    default ip list path.
    '''

    targetPath = os.getcwd() + '/' + 'iplist.cfg'
    iplist, namelist = getServerIpByReadFiles(targetPath)
    
    ip_Name_File(iplist, namelist)
    
    for i in range(20001, 20030):
        commonTcpProbeServer(iplist, namelist, i)

    if viewLinkServerIpList() is False:
        sys.exit(1)

    writeTCPServerLog()
    writeSystemLog()

    print('client exit')
    sys.exit(0)