linux - Expect 的 spawn 将 ssh 的 -i 解释为它自己的

标签 linux tcl expect

在 expect 中,有什么方法可以引用 spawn 运行的命令吗?将公钥从一个 AWS 实例推送到另一个 AWS 实例的 expect 脚本会操纵命令,使 ssh 的 -i 选项变为无效的 cat 选项。

脚本。

#!/usr/bin/expect -d 

spawn sudo -s cat /root/.ssh/id_rsa.pub | ssh -i /tmp/key.pem ec2-user@ip-50-101-23-6 sudo -s 'dd of=/root/.ssh/authorized_keys oflag=append conv=notrunc'
expect {
    "*yes/no*"    { send "yes\r"; exp_continue }
}

错误。

$ pushSSH.expect
expect version 5.44.1.15
argv[0] = /usr/bin/expect  argv[1] = -d  argv[2] = ./pushSSH.expect                        
set argc 0
set argv0 "./pushSSH.expect"
set argv ""
executing commands from command file ./pushSSH.expect
spawn sudo -s cat /root/.ssh/id_rsa.pub | ssh -i /tmp/key.pem ec2-user@ip-50-101-23-6 sudo -s 'dd of=/root/.ssh/authorized_keys oflag=append conv=notrunc'
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {13106}

expect: does "" (spawn_id exp4) match glob pattern "*yes/no*"? no
cat: invalid option -- 'i'
Try `cat --help' for more information.

expect: does "cat: invalid option -- 'i'\r\nTry `cat --help' for more information.\r\n" (spawn_id exp4) match glob pattern "*yes/no*"? no
expect: read eof
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) "cat: invalid option -- 'i'\r\nTry `cat --help' for more information.\r\n"

该命令在手动运行时是否有效?是的。

sudo -s cat /root/.ssh/id_rsa.pub | ssh -i /tmp/key.pem ec2-user@ip-50-101-23-6 sudo -s 'dd of=/root/.ssh/authorized_keys oflag=append conv=notrunc'
0+1 records in
0+1 records out
401 bytes (401 B) copied, 7.8214e-05 s, 5.1 MB/s

操作系统:Red Hat Enterprise Linux Server 6.7 版(圣地亚哥)

期待版本 5.44.1.15

最佳答案

Expect 的 spawn 命令直接执行它的参数而不将它们传递给 shell。这意味着像 i/o 重定向和管道这样的 shell 构造将不起作用。当你跑...

spawn sudo -s cat /root/.ssh/id_rsa.pub | ssh -i /tmp/key.pem ...

...expect 正在传递 /root/.ssh/id_rsa.pub 以及之后的所有内容 作为 cat 命令的参数。

如果你想运行一个 shell 管道,你需要显式地启动一个 shell 并将它传递给命令行:

spawn sh -c {sudo -s cat /root/.ssh/id_rsa.pub | ssh -i /tmp/key.pem ...}

例如:

expect1.7> spawn sh -c {echo hello world | sed s/world/nurse/}
spawn sh -c echo hello world | sed s/world/nurse/
14450
expect1.8> expect EOF
hello nurse
expect1.9> 

关于linux - Expect 的 spawn 将 ssh 的 -i 解释为它自己的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36658697/

相关文章:

c - 将堆栈移动到特定位置

c++ - 启动子进程中的竞争条件导致从管道读取挂起

linux - 如何在shell脚本中输入密码?

bash - 无密码登录

c - C 程序的日志记录

java - 将FileInputStream和FileOutputStream传给ffmpeg进行转码(使用JAVE-Java音视频编码)

c - 将 tcl.h 包含到 C 项目中

regex - TCL/Expect 正则表达式匹配多行输出

regex - Enter : expect -re "Press\[Enter\] to continue:" does not work的特殊含义

scripting - 自动化 GDB 调试 session 的最佳方法是什么?