有人可以告诉我为什么这个 shell 脚本没有按照我想要的方式工作吗
ssh hostname ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}'| xargs kill -KILL
当我运行这个时,我收到错误消息“kill:没有这样的进程”
但是当我运行这个时:
ssh hostname ps aux| egrep '.*python' | grep -v 'grep' |awk '{print $2}'| xargs echo
它正确地打印了 pid。并且
ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}' | xargs kill -KILL
在本地主机上也可以正常工作。
ssh hostname ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}'| xargs kill -KILL
When I run this I get the error message "kill: No such process"
But when I run this:
ssh hostname ps aux| egrep '.*python' | grep -v 'grep' |awk '{print $2}'| xargs echo
It correctly prints the pid. And also
ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}' | xargs kill -KILL
works correctly on the localhost.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的命令仅在远程主机上运行
ps aux
,其他所有内容都在本地执行。将其更改为
引号的使用将整个命令发送到远程主机。然后你必须在
$2
前面添加\
因为你在双引号内,而那些单引号只是此时的字符Your command is only running
ps aux
on the remote host, everything else gets executed locally.change it to
The usage of the quotes sends the entire command over to the remote host. And then you have to add the
\
in front of the$2
because youre inside double quotes, and those single quotes are just characters at that point正如其他人所指出的,您不能仅通过 ssh 运行管道命令而不将命令序列放在引号中。
但还有一种更简单的方法可以完成您想要的操作:
pkill 命令将为您处理所有进程 grep。
As the others have pointed out, you can't just run a piped command through
ssh
without putting the command sequence in quotation marks.But there's an even easier way to do what you want:
The
pkill
command will handle all of the process grepping for you.它不能那样工作,ssh 的输出是在本地计算机上处理的。因此,对kill 的调用将尝试终止您计算机上的进程,而不是远程计算机上的进程。
您可以尝试使用expect工具来解决问题。
It can't work that way, the output from ssh is processed on your local machine. So the call to kill will try to terminate a process on your machine, not on the remote machine.
You can try to use the expect tool to solve the problem.
这是因为只有第一个命令 (ps aux) 作为参数提供给 ssh。尝试使用引号:
ssh 主机名 "ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}'| xargs Kill -KILL"
在本例中为 "ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}'| xargs Kill -KILL" 将作为第二个参数传递给 ssh 命令
It's because only first command (ps aux) is being provided to ssh as args. Try to use quotes:
ssh hostname "ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}'| xargs kill -KILL"
In this case "ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}'| xargs kill -KILL" would be passed to ssh command as 2nd argument