不需要反引号的运行ssh复杂远程命令方式

Posted by 4Aiur on 06/07/2010 in Shell |

不需要反引号的运行ssh复杂远程命令方式

之前当我需要执行复杂的运程命令时,总是要先处理好引号、变量等问题,之后再执行命令写起来太麻烦,今天在commandlinefu上学了一招非常棒的方法,记录一下。

举个例子,之前需要用\反引$符号

[root@localhost ~]# ssh 127.0.0.1 -l root "echo a b c | awk '{print \$2}'"
b

现在我们可以把复杂的命令写到文件中执行。

[root@localhost ~]# cat cmd
echo a b c | awk '{print $2}'

方法1:

[root@localhost ~]# ssh 127.0.0.1 -l root "$(

方法2:

[root@localhost ~]# ssh 127.0.0.1 -l root "cat cmd"
b

方法3,使用标准输入执行,输入完毕后使用ctrl-D提交命令:

[root@localhost ~]# ssh 127.0.0.1 -l root "cat -"
hostname
if [ -d /root/ ];then
  echo "ok"
else
  echo "not ok"
fi
ctrl-D
localhost
ok
[root@localhost ~]#

直接把script嵌入到脚本中

[root@localhost ~]# ssh 127.0.0.1 -l root "$(cat 

来源:
http://www.commandlinefu.com/commands/view/5772/run-complex-remote-shell-cmds-over-ssh-without-escaping-quotes

ssh host -l user $(

run complex remote shell cmds over ssh, without escaping quotes
Much simpler method. More portable version:

ssh host -l user "cat cmd.txt"
perl -e 'system @ARGV, ' ssh host -l user 

run complex remote shell cmds over ssh, without escaping quotes

I was tired of the endless quoting, unquoting, re-quoting, and escaping characters that left me with working, but barely comprehensible shell one-liners. It can be really frustrating, especially if the local and remote shells differ and have their own escaping and quoting rules. I decided to try a different approach and ended up with this.

so we need to save the command in cmd.txt first and then run it?

there’s no way to do this? :

ssh host -l user $(perl -ane "print $F[1]\n" filename )

one alternative I can think of (not to save a file and then use "cat cmd.txt") is;

ssh host -l user "cat -"

And then type your command, press Enter and then ctrl-D. This will allow you run complex commands on remote machine without saving a file..

Tags: ,

Copyright © 2010-2024 4Aiur All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.