【问题标题】:How to pass command in command to pexpext in python如何将命令中的命令传递给python中的pexpect
【发布时间】:2015-10-23 15:31:46
【问题描述】:

我需要在 python 中执行这个命令并从键盘输入密码,这是可行的:

import os
cmd = "cat /home/user1/.ssh/id_rsa.pub | ssh user2@host.net \'cat >> .ssh/authorized_keys\' > /dev/null 2>&1"
os.system(cmd)

如您所见,我想通过 ssh 将公钥附加到远程主机。
见这里:equivalent-of-ftp-put-and-append-in-scp 和这里:copy-and-append-files-to-a-remote-machine-cat-error

当然我希望它在没有用户输入的情况下完成我已经尝试过 pexpect 并且我认为命令对它来说很奇怪:

import pexpect

child = pexpect.spawn(command=cmd, timeout=10, logfile=open('debug.txt', 'a+'))
matched = child.expect(['Password:', pexpect.EOF, pexpect.TIMEOUT])
if matched == 0:
    child.sendline(passwd)

在 debug.txt 中:

ssh-rsa AAAA..........vcxv233x5v3543sfsfvsv user1@host1
/bin/cat: |: No such file or directory
/bin/cat: ssh: No such file or directory
/bin/cat: user2@host.net: No such file or directory
/bin/cat: cat >> .ssh/authorized_keys: No such file or directory
/bin/cat: >: No such file or directory
/bin/cat: 2>&1: No such file or directory

我看到了两个解决方案:

  1. 修复 pexpect 命令,将整个字符串识别为一个命令,或者,
  2. 以假用户身份向标准输入注入/写入密码,但如何!?!?

【问题讨论】:

  • 不相关:Python中双引号内的单引号不需要转义:"_'|'_"
  • 你考虑过ssh-copy-id吗?
  • @J.F.Sebastian Nope,不可用。
  • ssh-copy-id is just a shell script。如果您安装了 openssh 客户端(ssh 命令),那么它应该可用。

标签: linux python-2.7 stdin pexpect


【解决方案1】:

来自the pexpect docs

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

child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
child.expect(pexpect.EOF)

【讨论】:

    【解决方案2】:

    这对我有用:

    command = "/bin/bash -c \"cat /home/user1/.ssh/id_rsa.pub | ssh user2@host.net \'cat >> ~/.ssh/authorized_keys\' > /dev/null 2>&1\""
    child = spawn(command=command, timeout=5)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-11
      • 2013-02-19
      • 1970-01-01
      • 2019-09-15
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      相关资源
      最近更新 更多