繁体   English   中英

Python sys.stdout.write()无法正常工作

[英]Python sys.stdout.write() not working

我正在尝试使用名为“ server.py”的父级python脚本来“ scp”一个名为“ whichserver.py”的子级python脚本。 我在父脚本中使用“子进程”。 父脚本将首先将子脚本“ SCP”到远程服务器中。 父脚本和子脚本都在同一目录中。 然后在远程服务器上运行子脚本,并在本地终端中显示输出。 但是我没有看到任何输出。 这是我的脚本:

父脚本“ server.py”:

import pexpect
import subprocess
import sys

def server_type(host):
  filepath = "whichserver"
  remotepath = "/tmp/"
  hostname = 'adam@' + host
  HOST = host
  COMMAND="cd /tmp && chmod 755 ./whichserver && ./whichserver"
  subprocess.call(['scp', filepath, ':'.join([hostname,remotepath])])
  ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)  
  result = ssh.stdout.readlines()
  if result == []:
      error = ssh.stderr.readlines()
      print >>sys.stderr, "ERROR: %s" % error
  else:
      print result
      for line in iter(result):
         sys.stdout.write(line)

print('Enter the server name: ')
hostname1 = raw_input()
response = os.system("ping -c 1 " + hostname1)

if response == 0:
  print(hostname1 + ' is up')
  server_type(hostname1)
else:
  print(hostname1 + ' is down')

我的孩子脚本称为“ whichserver.py”是:

#!/bin/bash
server="$(sudo dmidecode | grep -m1 'Manufacturer:' | sed 's/.*Manufacturer://')"
echo
printf $server

输出:

['\n']

预期产量:

ZT Systems

你能建议我为什么只换行符吗? 从远程服务器获取输出后,是否可以将值“ ZT Systems”存储在localhost中的变量中?

这里发生了一些事情。

  1. 除非ssh.stderr否则应使用ssh.communicate()代替ssh.stdoutssh.stderr 这样可以避免阻塞(有可能永远阻塞,因为您正在等待错误的管道)。

  2. 您应该检查子流程的输出状态。 相反,您只需检查它是否产生输出。 但是由于echo语句,即使失败,它也应该产生输出。 因此,对成功和失败的测试不起作用。

  3. 该shell脚本有点混乱。 它不会处理错误,它会将换行符放在有趣的地方。 有一个$server变量没有任何作用(好吧,除了去除空格)。

这是给您的固定外壳脚本:

#!/bin/sh
# Note: sh, because we don't need any bash-isms

# Exit on error
set -e

# No need to save to a variable, just print it out
# Also: printf would get rid of the newline at end, but why bother?
sudo dmidecode | grep -m1 'Manufacturer:' | sed 's/[^:]*: *//'

但是,这并不是必须的。 无需使用scp上传脚本并使用ssh执行脚本,我们只需使用ssh直接执行脚本即可。 这为我们节省了一些步骤。

from __future__ import print_function

def server_type(host):
    cmd = "sudo dmidecode | grep -m1 'Manufacturer:' | sed 's/[^:]*: *//'"
    proc = subprocess.Popen(
        ['ssh', str(host), cmd],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    if proc.returncode != 0:
        print('Error:', stderr.rstrip(), file=sys.stderr)
    else:
        print('Server type:', stdout.rstrip())

另请注意, sudo可能需要tty。 您可以将其配置为不需要tty,也可以使用ssh -t ,这使ssh提供了tty。 两种选择都有缺点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM