简体   繁体   中英

Send commands to a socket with Python

I am trying to connect to a socket file and send it some commands :

#!/usr/bin/env python

import socket

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/var/run/socket")
s.send('a command here')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

Did I miss something ?

I am totally new with Python.

Thanks in advance for any help !

You don't say what the actual problem is, or show any errors, but here are some things to check.

  1. Firstly, does the socket actually exist?
  2. Does your client python process have permission to access the socket file?
  3. Is there a server process running that is listening for incoming connections on that socket?

Note that you need a client and a server for communication to take place. The server must already be running before the client can connect. The server creates the socket which must not already exist.

server.py

import os
import socket

address = '/tmp/socket'
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.bind(address)      # this creates the socket file
s.listen(1)
r, a = s.accept()
r.send('Hello\n')
msg = r.recv(1024)
print msg
r.close()
s.close()
os.unlink(address)    # remove the socket file so that it can be recreated on next run

Run this server, then (in another terminal) run your client code:

client.py

import socket

server_addr = '/tmp/socket'
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(server_addr)
s.send('a command here')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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