首页 > 解决方案 > 遍历文件并发送超出预期的命令

问题描述

我正在尝试将命令从文件发送到设备超出预期。我尝试从本地机器一次发送一个,但我所有的文件路径都是相对于本地的,而不是相对于远程设备的。我的解决方案是尝试将文件上传到设备并从那里加载命令。当我尝试加载文件时,我不断收到权限问题,即使我从设备中捕获文件,读取它也没有问题。该文件每行有 1 个命令。

devicepath=rsync://root@localhost:$PORT_RSYNC/root/var/root/file.txt
/usr/bin/rsync -Pavr $1 $devicepath
    
expect <<- expect_feed
set  send_slow  {1  .001}
spawn ssh -o NoHostAuthenticationForLocalhost=yes -p $PORT_SSH root@localhost
expect -re "password:"
send -s "password\r"
expect -re $PROMPT_ROOT
send -s "chmod 777 /var/root/file.txt\r"
expect -re $PROMPT_ROOT
set f [cat /var/root/file.txt]
set cmds [split [read $f] "\n"]
close $f
foreach line $cmds {
    send -s "$line\r"
    expect -re $PROMPT_ROOT
expect_feed

这产生:

root# cat: /var/root/file.txt: Permission denied

我也试过

set f [open /var/root/file.txt]

...但它给出了同样的错误。

标签: bashsshexpect

解决方案


如果您发送的文件包含 shell 命令,请将其视为这样,并source在远程主机上简单地处理它

devicepath=rsync://root@localhost:$PORT_RSYNC/root/var/root/file.txt
/usr/bin/rsync -Pavr "$1" "$devicepath"

export PROMPT_ROOT PORT_SSH

expect << 'EXPECT_FEED'
    set send_slow {1  .001}
    spawn ssh -o NoHostAuthenticationForLocalhost=yes -p $env(PORT_SSH) root@localhost
    expect -re "password:"
    send -s "password\r"
    expect -re $env(PROMPT_ROOT)
    send -s ". /var/root/file.txt\r" ;# <<<<
    expect -re $env(PROMPT_ROOT)
    send "exit\r"
    expect eof
EXPECT_FEED

我更喜欢使用引用的 heredocs:shell 变量可以通过环境传递给期望。

我假设 root 的 shell 是一个 POSIX 类型的 shell,其中.是“源”命令。


推荐阅读