问题描述:

I'm trying to write a script which detects my current wifi connection and starts a socks proxy on my local computer.

The script itself works fine when I execute it by myself. Since I want everything to be automatically, I was thinking of using crontab. The only problem is that crontob itself doesn't have output or so, therefore the methods return an empty string.

Does anyone have a solution for this? My script looks like this:

#!/usr/bin/python

from subprocess import Popen, PIPE

import re, os

location = Popen(['networksetup', '-getcurrentlocation'], stdout=PIPE).stdout.read().split('\n')[0]

ssid = ''

for item in Popen(['/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport', '-I'], stdout=PIPE).stdout.read().splitlines():

if ' SSID' in item:

ssid = item.strip().split(': ')[-1]

if location != 'xyz' and ssid == 'abc':

# start socks proxy

pass

elif location == 'xyz' and ssid != 'abc':

# kill socks proxy

pass

print location, '|', ssid

I'm working on Mac OS 10.10.1 if somebody wants to know.

网友答案:

Actualy Popen should return process output both when you run it manyally and via cron.

  1. Try to redirect stderr to stdout inside Popend: stderr=sys.stdout.buffer (python3) and read the output, why command can't be exectued.

  2. Probably your script is run as root (if you edited /etc/crontab), try to change line to
    */10 * * * * Exceen python /Users/Exceen/Scripts/autoproxy.py

  3. Try to write full path to networksetup binary. Cron job can have different $PATH, missing /usr/bin/ (or wherever networksetup is)

相关阅读:
Top