如何将命令插入到位于远程服务器上的脚本中?

如何将命令插入到位于远程服务器上的脚本中?

我想使用with插入位于远程服务器上的rm $0脚本 ( ) 。但由于 expect 解释而失败。/home/user/config-scriptecho "rm $0" >> /home/user/config-scriptexpect$0

var1="rm \$0"
expect -c 'spawn ssh [email protected] ;expect "password" ; send "123456\n"; \
  expect "@"; send "sudo -k\n"; expect "@"; send "sudo su\n"; expect "password" ; \
  send "123456\n" ;expect "@"; send "echo '$var1'>>/home/user/config-script\n"; \
  expect "@"; send "exit\n"; send "logout\n"; interact'

有什么帮助吗?提前致谢。


missing "
    while executing
"send "echo rm"
couldn't read file "\$0>>/home/user/config-script\n"; expect "@"; send "exit\n"; send "logout\n"; interact": no such file or directory

事实上,在远程服务器上我有一个名为“ /home/user/config-script”的文件。就像这样:

#!/bin/bash
echo "my script"

最后,我希望这个脚本是:

#!/bin/bash
echo "my script"
rm $0

答案1

var1="rm \$0"使var1取值rm $0。然后在运行时expect尝试扩展。$0

为了解决这个问题,不要赋值var1。给它赋一个将扩展为 的rm $0值:expectrm $0

var1="rm \\\$0"

(或等价地var1='rm \$0':)

这使得var1的值变为rm \$0(这也许是您想要的)。然后该send "echo '$var1'>>/home/user/config-script\n";语句将导致正确的命令在远程计算机上运行:

echo 'rm $0'>>/home/user/config-script

最终结果如下:

var1='rm \\\$0'
expect -c 'spawn ssh [email protected] ;expect "password" ; send "123456\n"; \
      expect "@"; send "sudo -k\n"; expect "@"; send "sudo su\n"; expect "password" ; \
      send "123456\n" ;expect "@"; send "echo '"$var1"'>>/home/user/config-script\n"; \
      expect "@"; send "exit\n"; send "logout\n"; interact'

相关内容