简体   繁体   English

使用Expect自动执行管道命令

[英]use expect to automate the piped command

I want to automate a piped command cat ~/.ssh/id_rsa.pub | ssh root@host 'cat >> .ssh/authorized_keys' 我想自动化管道命令cat ~/.ssh/id_rsa.pub | ssh root@host 'cat >> .ssh/authorized_keys' cat ~/.ssh/id_rsa.pub | ssh root@host 'cat >> .ssh/authorized_keys' in expect . cat ~/.ssh/id_rsa.pub | ssh root@host 'cat >> .ssh/authorized_keys'expect When using spawn command to execute the command, 使用spawn命令执行命令时,

spawn cat ~/.ssh/id_rsa.pub | ssh root@host 'cat >> .ssh/authorized_keys' 

it throws error msg, 它抛出错误味精,

cat |: No such file or directory
cat ssh: No such file or directory
...

How should I spawn the piped commands? 我应该如何生成管道命令?

Because you want to technically execute multiple shell commands in one hit (and spawn doesn't handle the piped I/O), you need to encapsulate them in a script then use spawn to execute the script. 因为您想从技术上一次执行多个Shell命令(而spawn不能处理管道的I / O),所以您需要将它们封装在脚本中,然后使用spawn执行脚本。

The script you want already exists as ssh-copy-id, however if you want a trimmed down version you can create a script file on the fly then pass that into expect spawn: 您想要的脚本已经以ssh-copy-id的形式存在,但是,如果您想要一个精简的版本,则可以动态创建一个脚本文件,然后将其传递给Expect生成:

cat > /tmp/sshkeycopy.sh <<MYEOF
cat ~/.ssh/id_rsa.pub | ssh user@host 'mkdir -p -m 600 ~/.ssh; cat >> ~/.ssh/authorized_keys'
MYEOF

chmod u+x /tmp/sshkeycopy.sh

expect -c "
spawn /tmp/sshkeycopy.sh
expect { ... }"

With this bash example, the shell will handle the pipe as expected and just throw the password prompt out for expect to handle. 在此bash示例中,shell将按预期方式处理管道,并且仅将密码提示抛出以进行预期处理。

Does spawn handle input redirection? 是否spawn手柄输入重定向?

spawn ssh root@host "cat >> .ssh/authorized_keys" < ~/.ssh/id_rsa.pub

Input redirection would be preferred over using cat with a single file if you weren't using expect . 如果您不使用expect则输入重定向比使用cat与单个文件更可取。

Edit: use double quotes around cat command, instead of single quote (which does not work, as tested) 编辑:在cat命令周围使用双引号,而不是单引号(经测试无效)

您可以使用以下模式:

spawn bash -c "cat MEH | ssh root@host 'cat >>HMM' " 

This has been tested and works on Linux 这已经过测试并且可以在Linux上运行

#!/usr/bin/expect -f
set DOMAIN www.somedomain.tld
set TARFILE "[exec bash -c "echo $DOMAIN | cut -d'.' -f 1"].cert.tar"
puts "$TARFILE\r"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM