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

时间:2016-04-16 00:10:28

标签: linux tcl expect

预计,有没有办法引用spawn运行的命令?将公钥从一个AWS实例推送到另一个AWS实例的expect脚本,spawn操纵该命令,使得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

操作系统:红帽企业Linux服务器版本6.7(圣地亚哥)

期待版本5.44.1.15

1 个答案:

答案 0 :(得分:1)

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

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

...期望传递/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>