我最近用 Python 编写了一个程序(第一次尝试使用上述语言)从数据库中获取 IP 地址,使用 fping 对它们进行 ping 操作,并将响应时间返回到所述数据库中。应用程序在命令行中运行良好,但从 crontab 中断
任何帮助将不胜感激。谢谢
PYTHON 代码——我从互联网上得到了大部分
#!/usr/bin/env python
import MySQLdb as mdb;
import threading
import shlex
from subprocess import Popen, PIPE, STDOUT
import subprocess
con = mdb.connect('localhost', '*****', '*****', '*****')
class myThread(threading.Thread):
def __init__(self, ip_list):
threading.Thread.__init__(self)
self.ip_list = ip_list
def run(self):
get_ping(self.ip_list)
def get_simple_cmd_output(cmd):
args = shlex.split(cmd)
return Popen(args, stdout=PIPE, stderr=subprocess.STDOUT, shell=False).communicate()[0]
def get_ping(ip_list):
ip_response_dict = {}
cmd = "fping -C 4 -q {host}".format(host=" ".join(ip_list))
for x in get_simple_cmd_output(cmd).strip().split(' : ', 0) :
lines = x.split("\n")
for line in lines:
if line.upper().find(":", 0) > 0:
ip_data = line.split(":")
ip_address = ip_data[0].strip()
ip_response = ip_data[1].strip().split(" ")
total = 0;
length = 0;
for ping_time in ip_response:
if ping_time != '' and ping_time != '-':
total += float(ping_time)
length += 1
if total > 0 and length > 0:
ip_response_dict[ip_address] = (total / length)
else:
ip_response_dict[ip_address] = 0
save_ping_times(ip_response_dict)
def save_ping_times(ip_list):
cursor = con.cursor()
for key, value in ip_list.items():
cursor.execute('INSERT INTO `Tech_AP_Ping_Time`(`IP_Address`,`Value`) VALUES ("' + key + '","' + str(round(value, 2)) + '")')
con.commit()
threads = []
chunk_length = 100
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT `IP_Address` FROM `Tech_APs` WHERE (`IP_Address` IS NOT NULL AND `IP_Address` != '') ORDER BY `IP_Address`")
rows = cur.fetchall()
i = 0
ip_list = []
for row in rows:
ip_list.append(row['IP_Address'])
ip_list = [ip_list[i : i + chunk_length] for i in range(0, len(ip_list), chunk_length)]
for ip_chunk in ip_list:
thread = myThread(ip_chunk)
thread.start()
threads.append(thread)
CRON 命令 - 是的,我的实际 cron 中设置的脚本的完整路径
*/5 * * * * /usr/bin/python distro_pinger.py
错误——我从 cron 运行时得到这个
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/var/www/html/poller/distro_pinger.py", line 15, in run
get_ping(self.ip_list)
File "/var/www/html/poller/distro_pinger.py", line 25, in get_ping
for x in get_simple_cmd_output(cmd).strip().split(' : ', 0) :
File "/var/www/html/poller/distro_pinger.py", line 19, in get_simple_cmd_output
return Popen(['fping','-C','4','-q','','127.0.0.1'], stdout=PIPE, stderr=subprocess.STDOUT, shell=False).communicate()[0]
File "/usr/lib64/python2.6/subprocess.py", line 639, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1228, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
任何帮助都将不胜感激。(即使你告诉我我做错了一切:P)