Python在socket上发送cmd

时间:2009-12-20 14:14:49

标签: python sockets

我有一个关于Python的简单问题:

我有另一个Python脚本侦听Linux机器上的端口。 我已经做到了,所以我可以向它发送请求,它会通知另一个系统它还活着并且在听。

我的问题是我不知道如何从同一台机器上运行的另一个python脚本发送此请求(脸红)

我每分钟运行一个脚本,我想将其展开以发送此请求。我不希望得到回复,我的监听脚本会发布到数据库。

在Internet Explorer中,我这样写:http://192.168.1.46:8193/?Ping 我想知道如何从Python中执行此操作,并且如果其他脚本未运行,最好只发送而不挂起。

感谢 迈克尔

4 个答案:

答案 0 :(得分:4)

看起来您正在执行HTTP请求,而不是ICMP ping。

urllib2,内置于Python,可以帮助您实现这一目标。

你需要覆盖超时,这样你就不会停留太长时间。直接从上面的那篇文章中,这里有一些示例代码供您调整所需的超时和URL。

import socket
import urllib2

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

# this call to urllib2.urlopen now uses the default timeout
# we have set in the socket module
req = urllib2.Request('http://www.voidspace.org.uk')
response = urllib2.urlopen(req)

答案 1 :(得分:2)

import urllib2

try:
    response = urllib2.urlopen('http://192.168.1.46:8193/?Ping', timeout=2) 
    print 'response headers: "%s"' % response.info()
except IOError, e:
    if hasattr(e, 'code'): # HTTPError
        print 'http error code: ', e.code
    elif hasattr(e, 'reason'): # URLError
        print "can't connect, reason: ", e.reason
    else:
        raise # don't know what it is

答案 2 :(得分:0)

这有点不为我所知,但也许这个问题可能会有所帮助?

Ping a site in Python?

答案 3 :(得分:0)

考虑Twisted?你想要实现的目标可以直接从他们的examples中获取。这可能有点矫枉过正,但如果您最终想要开始添加身份验证,授权,SSL等,您也可以从这个方向开始。