加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

shell – pexpect – 在ssh上运行script.sh

发布时间:2020-12-15 20:58:11 所属栏目:安全 来源:网络整理
导读:我在编程上通过ssh运行本地脚本时遇到问题. 我不确定这是否是本地主机上的 shell变量替换的问题. 手动运行时 ssh monit@server1 'bash -s' /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh 我得到了预期的输出, CPU pctUser pctNice pctSystem pctIow
我在编程上通过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: No such file or directory

运行以下代码时,

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
Initial pexpect command output: 1
bash: /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh: No such file or directory

pexpect正在进入[pP] assword行,所以我猜密码正确传递,

解决方法

这里是pexpect手册的注释:

Remember that Pexpect does NOT interpret shell meta characters such as
redirect,pipe,or wild cards (>,|,or *). This is a common mistake.
If you want to run a command and pipe it through another command then
you must also start a shell.

这是工作线

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读