2017-06-12 144 views
2

情景如何通过bash脚本从远程服务器

的文件users.yml回用awk数组包含多个用户名和密码。一些用户名和密码正在重复。例如...

xxxxx 
username: abc 
password: abcpwd 
xxxxx 
xxxxx 
username: adam 
password: adampwd 
xxxxx 
xxxxx 
username: adam 
password: adampwd 
xxxxx 

脚本文件script.sh是试图让所有文件从users.yml用户名的条件相匹配的行号。

username='adam' 
filepath='/etc/myServer/users.yml' 

#Gets the line number for the username 
userNameLineNumbers=`awk -v line='^.*username: '$username'' '$0~line {print NR}' $filepath` 

echo "username line number: "$userNameLineNumbers #output: username line number: 6 10 

如果我在users.yml所在的同一台机器上运行脚本,该脚本工作正常。然而,问题是...

问题

如果我继续脚本另一台服务器上和脚本不起作用尝试从文件中获得的行号远程。

我尝试了几种方法来使用ssh来获得行号,但无法做到这一点。我不是bash脚本编写的专家,但仍以不同的方式尝试以下命令,每次都会给出一些奇怪的结果,而不是从文件中给出行号。

script="sudo awk -v line='^.*username: '$username'' '$0~line {print NR}' $filepath" 
userNameLineNumbers=$(ssh -o "StrictHostKeyChecking no" -tty -i "$PEM_FILE" "[email protected]" $script) 

期望的输出

寻找的溶液,以获得行号从文件其中awk的标准相匹配的远程服务器上的阵列。

我能想到的
+0

也许尝试使用'SSH -t' ... –

+0

@l” 'l','nope'ssh -t'也没有帮助 – wafers

+0

回复:“没有帮助”......它有什么作用? –

回答

0

两个变化:

  1. 使用eval$0运行里面$script变量

  2. 逃生$命令。否则,它被扩大到$0值,这给用于调用当前的shell(如:-bash

命令

script="sudo awk -v line='^.*username: '$username'' '\$0~line {print NR}' $filepath" userNameLineNumbers=$(ssh -o "StrictHostKeyChecking no" -tty -i "$PEM_FILE" "[email protected]" eval $script)

+0

感谢您的回答。但它不起作用。我添加了另一行“echo”username line number:“$ userNameLineNumbers”,它不会打印任何内容,甚至不会输入“username line number:”,脚本已经在ssh行中失败。 – wafers

相关问题