【问题标题】:can't re-establish connection to remote server after server restart | #pythonScript服务器重启后无法重新建立与远程服务器的连接| #python脚本
【发布时间】:2015-12-17 18:14:07
【问题描述】:

我正在尝试自动化基于 unix 的系统。我有一个带有自动化脚本的 python fabfile.py,它首先连接到远程服务器并运行脚本。在脚本之间,我有一个要求系统重新启动的命令。 此时,我正在失去与远程服务器的连接,无法重新建立连接。

--fabfile.py

//Import 

env.hosts = ['uname@host_ip']

def test() :

//here we run the commands

//calls reboot

//remaining commands

我可以在调用'reboot'命令后重新建立连接,以便执行剩余的命令吗?

【问题讨论】:

  • 在 stackoverflow.com 中学习格式化代码

标签: python ssh fabric


【解决方案1】:

那么这里还有其他东西在起作用,而不是织物。

Fabric 在程序上运行一切,意思是;如果您有要运行的事情的列表,fabric 将按顺序运行它们,并且当没有更多工作要做时,那么它之前不会断开连接。如果您遇到连接中断,请检查您的连接、服务器或服务器 ssh 配置。举个例子:

from fabric.api import run, task
from fabric.state import env

@task
def dev():
    """
    I REALLY like the environments done in a task and not global, its easier to override
    """
    env.hosts = ['10.99.0.2']
    env.user = 'vagrant'
    env.password = 'vagrant'
    env.key_filename = '~/.vagrant.d/insecure_private_key'

@task
def whoami():
    run('whoami')

@task
def echo(msg):
    run('echo "{}"'.format(msg))

简单测试:

$ fab dev whoami echo:'hello world'
[10.99.0.2] Executing task 'whoami'
[10.99.0.2] run: whoami
[10.99.0.2] out: vagrant
[10.99.0.2] out: 

[10.99.0.2] Executing task 'echo'
[10.99.0.2] run: echo hello world
[10.99.0.2] out: hello world
[10.99.0.2] out: 


Done.
Disconnecting from 10.99.0.2... done.

或者没有你仍然可以像这样运行它,因为你从来没有硬编码过它:

$ fab whoami echo:'hello world' -H 'vagrant@10.99.0.2','ubuntu@*****' --password vagrant -i ~/.ssh/*****.pem

请注意dev 任务未在此处运行。输出:

[vagrant@10.99.0.2] Executing task 'whoami'
[vagrant@10.99.0.2] run: whoami
[vagrant@10.99.0.2] out: vagrant
[vagrant@10.99.0.2] out: 

[ubuntu@*****] Executing task 'whoami'
[ubuntu@*****] run: whoami
[ubuntu@*****] out: ubuntu
[ubuntu@*****] out: 

[vagrant@10.99.0.2] Executing task 'echo'
[vagrant@10.99.0.2] run: echo "hello world"
[vagrant@10.99.0.2] out: hello world
[vagrant@10.99.0.2] out: 

[ubuntu@*****] Executing task 'echo'
[ubuntu@*****] run: echo "hello world"
[ubuntu@*****] out: hello world
[ubuntu@*****] out: 


Done.
Disconnecting from ubuntu@*****... done.
Disconnecting from vagrant@10.99.0.2... done.

【讨论】:

    【解决方案2】:

    您可以使用time.sleep(t)(其中t 是以秒为单位的时间)暂停您的脚本,直到您重新启动的机器恢复。

    【讨论】:

    • 当重启发生时连接会丢失,所以在唤醒之后。 Fabric 会重新建立连接吗?
    • @deepak 自己试试看?如果重新连接没有自动发生,请扩展您的代码来执行此操作。
    • 我评论后很快就试用了,发现效果很好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2016-08-12
    • 1970-01-01
    • 2016-05-25
    • 2020-04-06
    • 2014-09-27
    • 2012-10-17
    相关资源
    最近更新 更多