如何检查ssh命令是否通过pexpect spawn命令运行成功与否。

时间:2016-05-19 15:45:16

标签: python expect

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

此示例将代码写入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)

2 个答案:

答案 0 :(得分:0)

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

你可以做的另一件事是有多个期望,然后检查那些你想要的。例如:

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

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

答案 1 :(得分:0)

感谢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"