如何杀死由本地python脚本调用的远程子进程分叉的子进程(ex ssh)

时间:2017-10-17 11:19:53

标签: python linux ssh subprocess

我有一个python脚本,它将调用ssh进程来创建远程进程A.A将为服务器B创建一个ssh子进程。

当我运行脚本并按Ctrl-C中断它时,A将在远程端关闭。但是由A分叉的ssh仍然执行。 这是我的剧本:

import os
import inspect
import logging
import sys
import subprocess
import signal

CURRENT_DIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
PYTHON_PATH = '/usr/local/bin/python'
SNAPSYNC_PATH = CURRENT_DIR + '/snapsync.py'
EXECUTE_PATH = PYTHON_PATH + ' ' + SNAPSYNC_PATH


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    cmd = 'ssh -p 22 -C -oServerAliveInterval=600 -oServerAliveCountMax=3 remote_ip "a.py" '
    logging.info(cmd)
    try:
        handle = subprocess.Popen(cmd, bufsize=0, stdin=None, shell=True)

    except KeyboardInterrupt:
        print "Caught KeyboardInterrupt, terminating workers"
        handle.terminate()
        handle.kill()

我想知道当我按Ctrl-C到本地脚本时如何终止B进程?

0 个答案:

没有答案