使用 bash 脚本删除远程机器上的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7955521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete a file on a remote machine using bash script
提问by Amey
I want to basically copy files from remote machines, and after copying, delete them.
我想基本上从远程机器复制文件,复制后删除它们。
I have managed to copy the files using expect and scp. Also, managed to delete the files outside of the script, but not able to use the ssh command inside the script. This is what I have
我已经设法使用 expect 和 scp 复制文件。此外,设法删除了脚本外的文件,但无法在脚本内使用 ssh 命令。这就是我所拥有的
#!/usr/bin/expect -f
log_user 1
set timeout -1
set pass "pass"
spawn scp [email protected]:Desktop/LoginCheck/Login/* .
expect {
password: {send "$pass\r" ; exp_continue}
}
ssh [email protected] 'rm -rf Desktop/LoginCheck/Login/*'
expect {
password: {send "$pass\r" ; exp_continue}
}
So the scpsection of code works.
But the sshand rm -rfthis is the error for ssh
所以这scp部分代码有效。但是,ssh和rm -rf这是SSH的错误
invalid command name "ssh"
while executing
Can someone provide a working script?
有人可以提供一个工作脚本吗?
回答by Tanktalus
Shouldn't the ssh command be a new spawn? By the way, just reading the wikipedia article on expect, one of the "cons" listed is:
ssh 命令不应该是一个新的生成吗?顺便说一句,只需阅读关于 expect的维基百科文章,列出的“缺点”之一是:
A less obvious argument against Expect is that it can enable sub-optimal solutions. For example, a systems administrator needing to log into multiple servers for automated changes might use Expect with stored passwords, rather than the better solution of ssh agent keys. The ability to automate interactive tools is attractive, but there are frequently other options that can accomplish the same tasks in a more robust manner.
反对 Expect 的一个不太明显的论点是它可以启用次优解决方案。例如,需要登录多个服务器进行自动更改的系统管理员可能会使用带有存储密码的 Expect,而不是更好的 ssh 代理密钥解决方案。自动化交互式工具的能力很有吸引力,但通常还有其他选项可以以更强大的方式完成相同的任务。
Sounds like you're doing exactly the example sub-optimal solution. If you were using a proper ssh key pair, you wouldn't need expect at all.
听起来您正在执行示例次优解决方案。如果您使用的是正确的 ssh 密钥对,则根本不需要期望。
回答by Aaron Digulla
Replace sshwith spawn ssh- sshis not a built-in command of expect.
替换ssh为spawn ssh-ssh不是 的内置命令expect。
回答by thiton
You just missed the spawn in front of the ssh line:
你刚刚错过了 ssh 线前面的 spawn:
spawn ssh [email protected] 'rm -rf Desktop/LoginCheck/Login/*'
You should also add a waitline before it, potentially checking for the exit code of scp.
您还应该wait在它之前添加一行,可能会检查 scp 的退出代码。
In any case, don't use expect to automate ssh, use ssh keys and sh scripts like the other posters described.
在任何情况下,不要使用 expect 来自动化 ssh,使用 ssh 密钥和 sh 脚本,就像描述的其他海报一样。

