如何检查节点是否在线?

0 投票
1 回答
3873 浏览
提问于 2025-04-16 13:14

我想让我的脚本通过 [ssh] 远程登录到另一台机器上做点事情,但在此之前我想检查一下:这个节点不是本地机器,并且这个节点是在线的,否则就退出。有什么最简单的方法可以做到这一点吗?提前感谢你的建议。谢谢!!


更新-1 @Jakob: 错误信息

我是不是做错了什么?运行脚本时,我得到了这个:

File "./pingTest.py", line 9, in ?
    ping('10.0.11.20')
  File "./pingTest.py", line 5, in ping
    process = subprocess.Popen('ping %s' % target, stdout = subprocess.PIPE)
  File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.4/subprocess.py", line 996, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

在 v2.6 上也是同样的情况。谢谢!!


更新-2 @Jakob: 仍然不工作

所以,这就是现在的脚本,做了一些小修改:

#!/usr/bin/env python

import sys, subprocess
def ping(target):
    process = subprocess.Popen('ping -c 1 -A %s' % target, stdout = subprocess.PIPE, shell = True)
    results = process.communicate()[0]
    print(results)
    #return "Reply from %s" % target in results
    print "Reply from %s" % target in results

ping(sys.argv[1])

我稍微改了一下 ping 的语句,让它只发送一次 ECHO_REQUEST 数据包。还把 return 改成了 print,这样可以在屏幕上显示一些信息。运行脚本时,我得到了这个。

$ ./pingTest.py 10.0.11.1
PING 10.0.11.1 (10.0.11.1) 56(84) bytes of data.
64 bytes from 10.0.11.1: icmp_seq=1 ttl=64 time=0.665 ms

--- 10.0.11.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.665/0.665/0.665/0.000 ms

False

$ ./pingTest.py 10.0.11.2
PING 10.0.11.2 (10.0.11.2) 56(84) bytes of data.
From 10.0.11.20 icmp_seq=1 Destination Host Unreachable

--- 10.0.11.2 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms


False

10.0.11.1 是一个正常运行的主机(从第一个打印语句可以看出来),但它却显示 False - 我到底做对了吗?

如果我这样打印 results

for tx in results:
    print "Result: ", tx

我得到的 Result 是这样的:

Result:  P
Result:  I
Result:  N
Result:  G
Result:   
Result:  1
Result:  0
......
......

所以,它实际上做的事情似乎有点不对(??)。或者,也许我根本没能理解你的脚本。有什么评论或建议吗?谢谢!!

1 个回答

0

正如sven所说,我觉得有一种方法可以为套接字设置新的超时时间。所以只要连接上,如果超时了,就可以认为它是离线的。

编辑:

Code examples
import subprocess
def ping(target):
    process = subprocess.Popen('ping %s' % target, stdout = subprocess.PIPE)
    results = process.communicate()[0]
    return "Reply from %s" % target in results

撰写回答