I want my script to [ssh] remote login to a different machine to do something but before that I want to check: that node is not the localhost and the node is online, otherwise exit. What's the best [easiest??] way of doing that? Thanks for your advise in advance. Cheers!!
Update-1 @Jakob: Error message
Am I doing something wrong? Running the script, I get this:
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
The very same thing happens on v2.6 as well. Cheers!!
Update-2 @Jakob: Still not working
So, this is the script now, with some minor modification:
#!/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])
I changed the ping
statement a little bit, so that it sends ECHO_REQUEST packet just once. Also changed the return
to print
to get some information on the screen. And, this is what I get when I run the script.
$ ./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 is an up and running host (as you can see from the first print statement) but it's saying False
- am I actually doing it right?
If I actually print the results
this way:
for tx in results:
print "Result: ", tx
I get the Result
like this:
Result: P
Result: I
Result: N
Result: G
Result:
Result: 1
Result: 0
......
......
So, it's actually doing rather something else (??). Or maybe, I didn't able to follow your script at all. Any comment or suggestion? Cheers!!
As sven says. I think there is a method to set a new timeout on socket. So just connect and if it times out consider it offline.
EDIT:
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
精彩评论