用python / paramiko启动unix守护进程

时间:2016-11-07 14:40:43

标签: python unix paramiko

我的一台服务器上的服务有一个有趣的问题我需要通过我用Python编写的命令行工具来启动/停止。

脚本运行没有问题。它基本上使用Paramiko模块连接到服务器,使用所述模块的SSHClient执行命令并打印标准输出。

#!/usr/bin/python

from __future__ import print_function

import os
import sys
import paramiko

username = "root"
password = "TOPSECRET"
servicename = "xy"
server = "192.168.1.2"

sshclient = paramiko.SSHClient()
sshclient.load_system_host_keys()

sshclient.connect(server, username=username, password=password)

stdin, stdout, stderr = sshclient.exec_command("service servicename stop", get_pty=True)
stdin.close()
for line in stdout.read().splitlines():
    print(line)

执行此操作会给我一个类似

的输出
Service xy has stopped

这正是我的预期。如果服务预先运行,我现在在服务器上手动检查,它已经停止。所以代码工作得很好,正在做我想做的事。

但是,如果我将整个“停止”改为“开始”,那么上帝是禁止的:

stdin, stdout, stderr = sshclient.exec_command("service servicename start", get_pty=True)
stdin.close()
for line in stdout.read().splitlines():
    print(line)

执行此操作也会根据需要提供结果。 E.g:

Service xy has started

除了如果我现在尝试连接到所述服务器上的所述服务或手动检查,它没有运行。无论如何,在服务器上手动运行命令service xy start将启动服务。

是的 - 我知道它的不良做法,但我使用root帐户在脚本中启动/停止服务。这是为了确保它与任何权限问题无关。

老实说,我至少有点无能为什么停止工作正常,开始不会。有什么建议吗?

编辑:以下内容也会有趣地失败。场景:服务在命令执行时运行。

stdin, stdout, stderr = sshclient.exec_command("service servicename stop && service servicename start", get_pty=True)
stdin.close()
for line in stdout.read().splitlines():
    print(line)

这将停止服务,输出服务已停止的确认,然后FAILS启动服务,然后输出服务已启动。执行此操作后,服务未运行。

0 个答案:

没有答案
相关问题