Pexpect的 - 通过ssh运行script.sh(pexpect - run script.s

2019-09-16 14:52发布

我在运行程序通过ssh本地脚本的麻烦。
我不确定这是否是与本地主机上的shell变量替换的问题。

当手动运行,

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

我得到预期的输出,

CPU pctUser pctNice pctSystem pctIowait pctIdle
所有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 ....

但我得到

庆典:/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
庆典:/u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh:没有这样的文件或目录

Pexpect的被碰撞到[PP] assword线,所以我想密码正确传递,

Answer 1:

这里从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 - run script.sh over ssh