Ad

How To Use A Socket Created By Root With A Normal User

So I have this server:

import socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind('/tmp/sock.sock')
sock.listen(1)
while True:
    conn, ca = sock.accept()
    print(conn.recv(1024))

And this client:

import socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect('/tmp/sock.sock')
sock.send('Hello, World')

The actual sending and receiving is a bit more complex, but works perfectly, as long as both the server and client is run by root. It also works when the client is run as root and the server is run by a normal user. But when I try to run the server with root and client by normal user I get this:

$ python3 client.py
connecting to /tmp/sock.sock
[Errno 13] Permission denied

How can I solve this? The server need to be run as root and the client as an unprivileged user.

I have understood as much as that it has to do with file permissions for the socket file, but I cannot see how I should fix it. I could not see any options to pass to the socket constructor that would fix this.

Ad

Answer

Change file mode to allow anyone to access it. Add this lines in your server

import os
os.chmod("/tmp/sock.sock", 0o777)
Ad
source: stackoverflow.com
Ad