简体   繁体   English

Python在socket上发送cmd

[英]Python send cmd on socket

I have a simple question about Python: 我有一个关于Python的简单问题:

I have another Python script listening on a port on a Linux machine. 我有另一个Python脚本侦听Linux机器上的端口。 I have made it so I can send a request to it, and it will inform another system that it is alive and listening. 我已经做到了所以我可以向它发送一个请求,它会通知另一个系统它还活着并且在听。

My problem is that I don't know how to send this request from another python script running on the same machine (blush) 我的问题是我不知道如何从同一台机器上运行的另一个python脚本发送此请求(腮红)

I have a script running every minute, and I would like to expand it to also send this request. 我每分钟运行一个脚本,我想扩展它以发送此请求。 I dont expect to get a response back, my listening-script postes to a database. 我不希望得到回复,我的监听脚本会提到数据库。

In Internet Explorer, I write like this: http://192.168.1.46:8193/?Ping I would like to know how to do this from Python, and preferably just send and not hang if the other script is not running. 在Internet Explorer中,我这样写: http//192.168.1.468193 /?我想知道如何从Python中执行此操作,并且最好只是发送而不是挂起,如果其他脚本没有运行。

thanks Michael 谢谢迈克尔

It looks like you are doing an HTTP request, rather than an ICMP ping. 看起来您正在执行HTTP请求,而不是ICMP ping。

urllib2 , built-in to Python, can help you do that. urllib2 ,内置于Python,可以帮助您做到这一点。

You'll need to override the timeout so you aren't hanging too long. 你需要覆盖超时,这样你就不会拖得太久。 Straight from that article, above, here is some example code for you to tweak with your desired time-out and URL. 直接从上面的那篇文章中,这里有一些示例代码供您调整所需的超时和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)
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

This is a bit outside my knowledge, but maybe this question might help? 这有点超出我的意识,但也许这个问题可能会有所帮助?

Ping a site in Python? 用Python ping一个站点?

Considered Twisted ? 考虑扭曲 What you're trying to achieve could be taken straight out of their examples . 你想要实现的目标可以直接从他们的例子中获取 It might be overkill, but if you'll eventually want to start adding authentication, authorization, SSL, etc. you might as well start in that direction. 它可能有点矫枉过正,但如果您最终想要开始添加身份验证,授权,SSL等,您也可以从这个方向开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM