2016-09-21 40 views
1

我已经广泛搜索了这个答案,但它似乎仍然躲过我。 我想写一个bash脚本来检查是否有多个ip:port服务器是活着的。 平安不支持不同端口(据我所知),我发现了一个漂亮的蟒蛇1衬垫可以融入庆典:调用bash中的python进程,然后将输出捕获到变量中

portping() { python <<<"import socket; socket.setdefaulttimeout(1); socket.socket().connect(('$1', $2))" 2> /dev/null && echo OPEN || echo CLOSED; } 

这将创建一个功能portping可以从bash脚本中调用,我然后要在包含主机列表的txt文件使用:

Contents of hosts.txt 
myserver.host.com 3301 
myserver.host.com 3302 

我则希望bash脚本从HOSTS.TXT两个变量$读取IP和端口$,portping这些变量,然后存储呼应将'OPEN'或'CLOSED'结果导入变量以进一步操作(发送pushbullet消息告诉我服务器已关闭)。

while read ip port; 
do 
    echo "Checking if $ip port $port is alive" 
    portping $ip $port # debug check to see if python function is actually working 
    status = 'portping $ip $port' # herein lies my issue, how do I get the python functions echo output into the variable ? 
    echo "$ip $port is $status" 
    if [ "$status" == "CLOSED" ] 
     then 
     echo "Sending pushbullet notification" 
     # pushbullet stuff; 
    else 
     echo "It's Alive!" 
    fi 
done < ${HOSTS_FILE} 

但是我得到的输出是这样的:

$ ./pingerWithPython.sh hosts.txt 
Using file hosts.txt 
Checking if myserver.host.com port 3301 is alive 
OPEN 
status: Unknown job: = 
myserver.host.com 3301 is 
It's Alive! 
Checking if myserver.host.com port 3302 is alive 
CLOSED 
status: Unknown job: = 
myserver.host.com 3302 is 
It's Alive! 

谎言!它不活着:) 显然问题是与状态=行。对此我必须有一个简单的解决方法,但我也无法解决这个问题!

+0

要么改变单引号反引号,或使用'富= “$(execute_me ARG1 ARG2)”'语法 – Jameson

+0

你的术语是困惑。 'ping'不支持端口号,因为它不使用具有它们的协议。如果你想尝试通过TCP连接到一个特定的端口,看看例如'nc -z'(又名'netcat')。 – tripleee

+0

Offtopic,当你看到python做你需要的东西时;把整个事情写成python脚本不是更合理吗? – GhostCat

回答

2

要获得变量的命令的结果,你需要使用反引号('),而不是简单引号('),或$()成语:

status=`portping $ip $port` 

status=$(portping $ip $port) 

在等号周围没有空格

+0

尝试了自己和詹姆森的建议,但输出仍然是一样的。它可能与Python的声明本身有关吗? – theCheek

+0

对不起错过了空格评论 - 显然我是新来的bash和它的pinnikitiness是我正在慢慢学习的东西!感谢您的帮助,现在就开始工作。 – theCheek