输出JSON从Bash脚本 [英] Output JSON from Bash script
问题描述
所以我有一个庆典
脚本,它输出的服务器的详细信息。问题是,我需要的输出为 JSON
。什么是去这个问题的最好方法是什么?下面是bash脚本:
So I have a bash
script which outputs details on servers. The problem is that I need the output to be JSON
. What is the best way to go about this? Here is the bash script:
# Get hostname
hostname=`hostname -A` 2> /dev/null
# Get distro
distro=`python -c 'import platform ; print platform.linux_distribution()[0] + " " + platform.linux_distribution()[1]'` 2> /dev/null
# Get uptime
if [ -f "/proc/uptime" ]; then
uptime=`cat /proc/uptime`
uptime=${uptime%%.*}
seconds=$(( uptime%60 ))
minutes=$(( uptime/60%60 ))
hours=$(( uptime/60/60%24 ))
days=$(( uptime/60/60/24 ))
uptime="$days days, $hours hours, $minutes minutes, $seconds seconds"
else
uptime=""
fi
echo $hostname
echo $distro
echo $uptime
所以我想输出是一样的东西:
So the output I want is something like:
{"hostname":"server.domain.com", "distro":"CentOS 6.3", "uptime":"5 days, 22 hours, 1 minutes, 41 seconds"}
感谢。
推荐答案
替换你的三个回声
在你的脚本与命令的结束:
Replace your three echo
commands at the end of your script with:
echo -e "{\"hostname\":\""$hostname"\", \"distro\":\""$distro"\", \"uptime\":\""$uptime"\"}"
或此:
printf '{"hostname":"%s","distro":"%s","uptime":"%s"}\n' "$hostname" "$distro" "$uptime"
一些较新的发行版,有一个名为:的/ etc / LSB释放
或类似的名称(猫的/ etc / *释放
)。因此,你可以的可能的依赖与弄死你对Python的:
Some of the more recent distros, have a file called: /etc/lsb-release
or similar name (cat /etc/*release
). Therefore, you could possibly do away with dependency your on Python:
distro=$(awk -F= 'END { print $2 }' /etc/lsb-release)
顺便说一句,你应该使用反引号做了。他们有点老气。
An aside, you should probably do away with using backticks. They're a bit old fashioned.
这篇关于输出JSON从Bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!