为什么结构会在每个命令后重新连接?

时间:2016-06-25 03:43:31

标签: python fabric

我正在使用fabric来自动部署。

我使用此Fabric命令连接到我的远程服务器:

fab deploy:host=user@host.com:1234 -i ~/.ssh/ssh_key.pem

问题在于,每当我运行Fabric命令时,它都会断开与我的服务器的连接,并再次重新连接到它以运行下一个命令。

这是我的代码,我正在使用fabric3:

from fabric.contrib.files import append, exists, sed
from fabric.api import env, local, run
import random

REPO_URL = 'https://github.com/imhuwq/djangor.git'

env.use_ssh_config = True


def deploy():
    site_folder = '/home/%s/sites/%s' % (env.user, env.host)
    source_folder = site_folder + '/source'
    _create_directory_structure_if_necessary(site_folder)
    _get_latest_source(source_folder)
    _update_settings(source_folder, env.host)
    _update_virtualenv(source_folder)
    _update_static_files(source_folder)
    _update_database(source_folder)


def _create_directory_structure_if_necessary(site_folder):
    for subfoler in ('database', 'static', 'virtualenv', 'source'):
        run("mkdir -p %s/%s" % (site_folder, subfoler))


def _get_latest_source(source_folder):
    if exists('%s/.git' % source_folder):
        run("cd %s && git fetch" % source_folder)
    else:
        run("git clone %s %s" % (REPO_URL, source_folder))
        current_commit = local("git log -n 1 ==format=%H", capture=True)
        run("cd %s && git reset --hard %s" % (source_folder, current_commit))


def _update_settings(source_folder, site_name):
    settings_path = source_folder + '/superlists/settings.py'
    sed(settings_path, "DEBUG = True", "DEBUG = FALSE")
    sed(settings_path,
        'ALLOWED_HOSTS = .+$',
        'ALLOWED_HOSTS = ["%s"]' % site_name)

    secret_key_file = source_folder + '/superlists/secret_key.py'
    if not exists(secret_key_file):
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_+=)'
        key = ''.join(random.SystemRandom().choice(chars) for _ in range(50))
        append(secret_key_file, "SECRET_KEY = '%s'" % key)
    append(settings_path, '\nfrom .secret_key import SECRET_KEY')


def _update_virtualenv(source_folder):
    virtualenv_folder = source_folder + '/../virtualenv'
    if not exists(virtualenv_folder + '/bin/pip'):
        run('virtualenv --python=python3 %s' % virtualenv_folder)
    run('%s/bin/pip install -r %s/requirements.txt'
        % (virtualenv_folder, source_folder))


def _update_static_files(source_folder):
    run("cd %s %% ..virtualenv/bin/python3 manage.py collectstatic --noinput"
        % source_folder)


def _update_database(source_folder):
    run('cd %s && ../virtualenv/bin/python3 manage.py migrate --noinput'
        % source_folder)

0 个答案:

没有答案