Javier Javier - 4 months ago 16
Python Question

Code works in console, but not when run by cron

When I run this code works fine for console. It produces no error.

import sh
import uuid
import urllib

print 'Ip ....'
# Print only IP address from specific interface
LineaX = sh.grep(sh.ifconfig('eth0'), '-oP', '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
# Asignar Variables
IpX = LineaX.splitlines()[0]
PuertaX= LineaX.splitlines()[1]
MascaraX = LineaX.splitlines()[2]
MacX = ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1])
DataX = open('/etc/resolv.conf').read().split()
for item in DataX:
if len( item.split(".") ) == 4:
Dns1X = item
Dns2X = ''
# Actualizar informacion
urllib.urlopen('http://www.miurl.com/file.php?mac='+ MacX + '&ip=' + IpX + '&mascara='+ MascaraX + '&puerta='+ PuertaX + '&dns1='+ Dns1X + '&dns2='+ Dns2X )
print 'Ip ... OK'

In cronjob produces this error:

Traceback (most recent call last):
File "/home/pi/system/sensor_ip.py", line 7, in <module>
LineaX = sh.grep(sh.ifconfig('eth0'), '-oP', '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
File "/usr/local/lib/python2.7/dist-packages/sh.py", line 2301, in __getattr__
return self.__env[name]
File "/usr/local/lib/python2.7/dist-packages/sh.py", line 2232, in __getitem__
return Command._create(k, **self.baked_args)
File "/usr/local/lib/python2.7/dist-packages/sh.py", line 776, in _create
raise CommandNotFound(program)
sh.CommandNotFound: ifconfig

What do I have that is wrong?


With sh you need to import the commands you need, e.g.:

from sh import ifconfig

That's why you're seeing the error:

sh.CommandNotFound: ifconfig

If it's working fine on the shell but not in cron the issue is that you need to specify the absolute path to the binary because crons don't have a path.