【搬家】【Python】Python 实现自动 Ping 目标地址

来源:互联网 发布:网络布线工程 编辑:程序博客网 时间:2024/06/06 01:21

本文最早于 2013年8月29日于本人个人博客(http://mooowooo.tk)发表,现博客搬家至此,转载请注明出处。

昨天应公司网管部门的同事需要,使用 Python 写了一个 Ping 指定 IP,并在 连续5次不通 的情况下,通过telnet 连接 重启AP 的脚本,现在将代码分享如下。因为公司使用的平台都是Windows的,所以有的地方可以看出是 Windows,如果有朋友需要在其他平台使用,请注意修改部分命令和语句细节。因为对 Python 还不熟悉,所以写得十分丑陋,请见谅。之后会抽空重构的。

import os, sys, time, telnetlibfLog = 'Log.log'def main(configFilePath):    try:        getIP = open(configFilePath,'r')        # should be read(), if use readlines() will result some errors.        # split() must use sign '\n' to split the line, other wise it will drop some null/'' elements.        IP = getIP.read().split('\n')        if pingFun(IP[1]) <> True:            telnetFun(configFilePath)    except IOError, e:        print '''\n        -------------------- ERROR --------------------\n        Could not found the ConfigFile !\n        Please read the ReadMe.txt\n        make sure the PATH of ConfigFile is right AND TRY AGAIN !\n        This error has been writen into the Log File.\n        -----------------------------------------------'''        # write the log file.        getIP = open(fLog,'a')        strLog = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))        strLog = strLog + '\t\t IO Error\t\tCould not open ConfigFile.\n'        getIP.write(strLog)    finally:        getIP.close()def writeLog(logFilePath,strLog):    strLog = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+'\t\t'+strLog    wrtLog = open(logFilePath, 'a')    wrtLog.write(strLog)    wrtLog.close()def pingFun(strIP):    loopTime = 0    failTime = 0    while loopTime <= 4:        ping = os.system('ping -n 1 ' + strIP)    # For Windows use        if ping == 0:            loopTime = 5            strLog = ' Ping OK\t\tPing %s OK.\n' % strIP            writeLog('Log.log',strLog)            return True        else:            loopTime = loopTime + 1            failTime = failTime + 1            time.sleep(1)    if failTime == 5:        strLog = 'Ping Fail\t\tPingt %s Fail.\n' % strIP        writeLog(fLog, strLog)        return Falsedef telnetFun(localPath):    print '1---\tTelnet function start.'    # read config file    configFile = open(localPath,'r')    try:        fileInfo = configFile.read().split('\n')    finally:        configFile.close()    # add command 'quit' to make sure the telnet can be quit before close the telnet stream.    fileInfo.append('quit')    # time.sleep(1)    host = fileInfo[2]    port = fileInfo[3]    username = fileInfo[4]    pwd = fileInfo[5]    # read config file fin.    print '2---\tRead config file finished.'    # time.sleep(1)    tn = telnetlib.Telnet(host, port, 10)    #tn = telnetlib.Telnet(host)    # Login part    if username <> '':    tn.read_until(b'Login: ')    tn.write(username.encode('UTF-8') + b'\r\n')    tn.read_until(b'Password: ')    tn.write(pwd.encode('UTF-8') + b'\r\n')    # Login part fin.    print '3---\tLogin success.'    # time.sleep(1)    # command part    cmdLoop = len(fileInfo)-8    command = fileInfo[7:]    loopTime = 0    while cmdLoop >= loopTime:        tn.read_until(b'>')        print '4-%d-\t%s.' % (loopTime, command[loopTime])        if command[loopTime] <> '':            tn.write(command[loopTime].encode('UTF-8') + b'\r\n')            time.sleep(1)        if command[loopTime] == 'quit':            break        loopTime = loopTime+1    # write result in files.    # TODO: write log files.    print '5---\tLogout success.'# time.sleep(1)    tn.close()    # close the stream    print '6-1-\tConnection close success.'    print '6-2-\tTelnet function finished.'    strLog = 'CommandsOK\t\tCommands Excute OK.\n'    writeLog(fLog, strLog)        time.sleep(1)if __name__ == '__main__':    main('config.ini')

下面是配置文档,根据需要修改。

[pingIP, telnetIP, port, username, password]127.0.0.1127.0.0.123userpwd[telnet commands]quit


0 0
原创粉丝点击