所以我目前正在试图获得一个脚本工作,但是当我手动运行时,它的行为与从crontab运行时相比有所不同。 基本上,我有一个反向的SSH隧道build立从一台服务器到另一台,并为了validation我的隧道是我:
我知道有更好的方法来validationSSH隧道(如autossh和ServerKeepAlive),但是对于策略和冗余问题,我必须这样做。 无论如何,这是脚本:
from __future__ import print_function from __future__ import absolute_import import os, sys, subprocess, logging, pexpect COMMAND_PROMPT = '[#$] ' TERMINAL_PROMPT = '(?1)terminal type\?' TERMINAL_TYPE = 'vt100' SSH_NEWKEY = '(?i)are you sure you want to continue connecting' SERVERS = [{address':'192.168.100.10', 'connString':'ssh [email protected]', 'testGet':'wget http://192.168.100.11/test.html -t 1 -T 10', 'tunnel':'start_tunnel'}, {address':'192.168.100.12', 'connString':'ssh [email protected]', 'testGet':'wget http://192.168.100.13/test.html -t 1 -T 10', 'tunnel':'start_tunnel2'}] def main(): global COMMAND_PROMPT, TERMINAL_PROMPT, TERMINAL_TYPE, SSH_NEWKEY, SERVERS #set up logging log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) handler = logging.FileHandler('/home/user/tunnelTest.log') formatter = logging.Formatter('%(asctime)s - %(module)s.%(funcName)s: %(message)s') handler.setFormatter(formatter) log.addHandler(handler) for x in SERVERS: #connect to server child = pexpect.spawn(x['connString']) i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, COMMAND_PROMPT, '(?i)password']) if i == 0: #Timeout log.debug('ERROR! Could not log in to ' + x['address'] + ' ...') sys.exit(1) if i = 1: #No key cached child.sendline('yes') child.expect(COMMAND_PROMPT) log.debug('Connected to ' + x['address'] + '...') if i = 2: #Good to go log.debug('Connected to ' + x['address'] + '...') pass #Housecleaning child.sendline('cd /tmp') child.expect(COMMAND_LINE) child.sendline('rm -r test.html') child.expect(COMMAND_LINE) log.debug('Testing service using ' + x['testGet'] + ' ...') child.sendline(x['testGet']) child.expect(COMMAND_PROMPT) if 'saved' in child.before.lower(): log.debug('Tunnel working, nothing to do here!') log.debug('Disconnecting from remote host ' + x['address'] + '...') child.sendline('exit') else: log.error('Tunnel down!') log.debug('Disconnecting from remote host ' + x['address'] + ' and restarting tunnel') child.sendline('exit') subprocess.call(['start',x['tunnel']]) log.debug('Autossh tunnel restarted') if __name__ == "__main__": main()
我的crontab条目如下:
0,30 * * * * python /home/user/tunnelTest.py
所以是的 – 这个脚本运行良好,当我手动(sudo python tunnelTest.py),并且也运行良好的crontab,除非隧道closures。 当一条隧道倒塌时,我会得到“隧道下来!” 和“从远程主机192.168.100.10断开连接并重新启动隧道”消息在我的日志中,但脚本似乎死在那里。 隧道不会重新启动,直到下一次计划运行开始时,我的日志中才会收到消息。
start_tunnel脚本位于/ etc / init中,testTunnel.py脚本位于/ home / user,testTunnel.log文件位于/ home / user / logs,并以root用户身份运行crontab -e。
任何深入了解这个问题将不胜感激。
谢谢!
你需要使用Python的完整path例如
/usr/bin/python
你可以找出which python的path
所以你的crontab条目看起来像
0,30 * * * * /usr/bin/python /home/user/tunnelTest.py