pexpect - 通过ssh运行script.sh脚本

4
我在通过ssh编程方式运行本地脚本时遇到了问题。
我不确定这是否是本地主机上的shell变量替换问题。

手动运行时,

ssh monit@server1 'bash -s' < /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh

我得到了预期的输出, ``` CPU pctUser pctNice pctSystem pctIowait pctIdle all 11.21 0.00 1.50 0.31 86.98 0 0.00 0.00 0.00 0.00 100.00 1 3.00 0.00 1.00 0.00 96.00 .... ``` 但是在运行以下代码时,我收到了“ bash:/u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh:没有这样的文件或目录” 的错误提示。
splunk_bin_dir = '/u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin'
hostname = 'server1'
username = 'monit'
password = 'monit#_'


command = "/usr/bin/ssh %(username)s@%(hostname)s 'bash -s' < %(splunk_bin_dir)s/cpu.sh" % locals()
print command

ssh_new_conn = 'Are you sure you want to continue connecting'

p = pexpect.spawn(command, timeout=360)
# Handles the 3 possible connection outcomes:
# a) Ssh to the remote host for the first time, triggering 'Are you sure you want to continue connecting'
# b) ask you for password
# c) No password is needed at all, because you already have the key.
i = p.expect([ssh_new_conn,'[pP]assword:',pexpect.EOF])
print ' Initial pexpect command output: ', i
if i == 0:
    # send 'yes'
    p.sendline('yes')
    i = p.expect(['[pP]assword:',pexpect.EOF])
    print 'sent yes. pexpect command output', i
    if i == 0:
        # send the password
        p.sendline(password)
        p.expect(pexpect.EOF)
elif i == 1:
    # send the password
    p.sendline(password)
    p.expect(pexpect.EOF)
elif i == 2:
    print "pexpect faced key or connection timeout"
    pass

print p.before

这是打印输出的内容,

/usr/bin/ssh monit@server1 'bash -s' < /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh
初始 pexpect 命令输出:1
bash: /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh: 没有那个文件或目录

pexpect 在 [pP]assword 行遇到问题,所以我猜密码已经正确传递了。

1个回答

4

这是来自pexpect手册的注意事项:

请记住,Pexpect不会解释shell元字符,例如重定向、管道或通配符(>、|或*)。这是一个常见错误。如果您想运行一个命令并将其通过另一个命令进行管道传输,则必须同时启动shell。

以下是可行的行:

command = """/bin/bash -c "/usr/bin/ssh  %(username)s@%(hostname)s 'bash -s' < %(splunk_bin_dir)s/cpu.sh" """ % locals()

非常感谢!我之前并不知道 Pexpect 还有这个“特性”。 - Joao Figueiredo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接