Python OpenWRT 定时任务

1 投票
2 回答
2375 浏览
提问于 2025-04-16 08:48

我正在尝试在OpenWrt设备上运行一个Python脚本:

#!/root/system/usr/bin/python
import subprocess

p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","-Ln", "192.168.1.1","1.3.6.1.2.1.2.2.1.10.7"], stdout=subprocess.PIPE).communicate()[0]
data = [r"curl","-d","iface_id=1&content="+ str(p).rstrip() ,"http://192.168.1.5:8080/stat/add_istat/"]
a = subprocess.Popen(data, stdout=subprocess.PIPE).communicate()[0]

这个脚本通过snmp获取数据,然后用curl把数据发送到本地服务器。 从命令行运行时一切正常:

root@OpenWrt:~/python# ./w.py 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0    34    0     6    0    28     31    146 --:--:-- --:--:-- --:--:--     0

我可以在数据库里看到数据。 但是从定时任务(cron)运行时:

0-55/5 * * * * /root/python/w.py

我在日志中看到了:

Dec 20 23:30:01 OpenWrt cron.err crond[1039]: USER root pid 16141 cmd /root/python/w.py

但是数据库里没有数据 :( 而且httpd的访问日志里也没有 :( 这是为什么呢?

2 个回答

0

我把 curl 替换成了 Python 的 urllib 请求,现在它可以正常工作了! :)

url = 'http://192.168.1.5:8080/stat/add_istat/"' # write ur URL here

values = {'iface_id' : '1', #write ur specific key/value pair
          'content' : str(p).rstrip(),
         }
try:
   data = urllib.urlencode(values)
   req = urllib2.Request(url, data)
   response = urllib2.urlopen(req)
   the_page = response.read()
   print the_page
except Exception, detail:
   print "Err ", detail
1

是不是因为snmpget或curl没有在cron的路径里呢?

撰写回答