Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python send cmd on socket

Tags:

python

sockets

I have a simple question about Python:

I have another Python script listening on a port on a Linux machine. 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)

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.

thanks Michael

like image 202
Reiler Avatar asked Feb 10 '26 07:02

Reiler


2 Answers

It looks like you are doing an HTTP request, rather than an ICMP ping.

urllib2, built-in to Python, can help you do that.

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.

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)
like image 61
Oddthinking Avatar answered Feb 13 '26 00:02

Oddthinking


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
like image 44
jfs Avatar answered Feb 13 '26 00:02

jfs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!