【问题标题】:how to check if ssh command ran through pexpect spawn command ran successfully or not .如何检查 ssh 命令是否通过 pexpect spawn 命令运行成功与否。
【发布时间】:2016-05-19 15:45:15
【问题描述】:

我正在编写一个简单的 python 脚本来测试与在它们上运行 centos 的多个 linux 主机的连接性。为此,我正在考虑使用 pexpect 模块和 ssh 。 pexpect 将在提示时发送存储在变量中的密码。问题是如何检查密码是否被成功接受。有没有办法这样做。代码如下。请添加您的专家 cmets。

此示例仅将代码写入 ssh 到 localhost。因此尚未包含 for 循环。

import pexpect
from getpass import getpass
import sys

# Defining Global Variables

log_file = '/tmp/AccessValidation'

# Getting password from user and storing in a variable 

passs = getpass("Please enter your password: ")

# Connect to server using ssh connection and run a command to verify access.

child = pexpect.spawn("ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1 'uptime'")
child.expect('Password:')
child.sendline(passs)

【问题讨论】:

    标签: python expect


    【解决方案1】:

    您可以做的其中一件事是为命令提示符设置一个expect。因此,如果您的提示是:someuser@host$,您可以使用child.expect(".*\$")

    您可以做的另一件事是有多个期望,然后将它们与您想要的进行检查。例如:

    i = child.expect([".*\$", "Password Incorrect"])
    if i != 0:
        print "Incorrect credentials"
    else:
        print "Command executed correctly"
    

    您可以在Pexpect's readthedocs page. 中查看一些examples Pexpect 还具有专门用于处理ssh 连接的pxssh 类,并且可能也有一些用处。我个人没有使用过它,但语法似乎相同,只是有更多与 ssh 相关的选项。

    【讨论】:

      【解决方案2】:

      感谢 Cory Shay 帮助我找出解决问题的正确方法。以下是我编写的代码,它有效。

      import pexpect
      from getpass import getpass
      import sys
      
      # Defining Global Variables
      
      log_file = '/tmp/AccessValidation'
      
      # Getting password from user and storing in a variable 
      
      passs = getpass("Please enter your password: ")
      
      # Connect to server using ssh connection and run a command to verify access.
      
      child = pexpect.spawn("ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1 'hostname' ")
      child.expect('Password:')
      child.sendline(passs)
      
      result = child.expect(['Password:', pexpect.EOF])
      if result == 0:
          print "Access Denied"
      elif result == 1:
          print "Access Granted"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-21
        • 2014-09-28
        • 2017-11-17
        • 2017-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-08
        相关资源
        最近更新 更多