用于从服务器接收信息的Python套接字?

时间:2017-09-20 18:02:03

标签: python sockets

在Windows中,我目前正致力于客户端/服务器程序。客户端程序向服务器发送Windows用户名。服务器程序使用os.system来运行“网络用户”。命令用户名。这很有效。

我想让服务器从Windows' net user'中发送结果。命令返回客户端客户端。 以下是我的工作计划:

client.py

import sys
from socket import socket, AF_INET, SOCK_DGRAM

SERVER_IP   = '10.x.xxx.xxx'
PORT_NUMBER = 2000
SIZE = 1024
print ("Test client sending packets to IP {0}, via port {1}\n".format(SERVER_IP, PORT_NUMBER))

myMessage1 = input(' Please enter your login name: ')

mySocket = socket( AF_INET, SOCK_DGRAM )
mySocket.sendto(myMessage1.encode('ascii'),(SERVER_IP,PORT_NUMBER))

sys.exit()

server.py

    import subprocess

    import os
    from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM
    import sys

    PORT_NUMBER = 2000
    SIZE = 1024

    hostName = gethostbyname( '0.0.0.0' )

    mySocket = socket( AF_INET, SOCK_DGRAM )
    mySocket.bind( (hostName, PORT_NUMBER) )

    print ("Test server listening on port {0}\n".format(PORT_NUMBER))

    # Receive no more than 1024 bytes


    while True:
        (data,addr) = mySocket.recvfrom(SIZE)
        print (data.decode())
        batcmd=('net user ' + data.decode() + ' /domain')
        result = os.system(batcmd)

        sys.exit()

现在我正在尝试添加:

client2.py

import os
import sys
from socket import socket, AF_INET, SOCK_DGRAM

SERVER_IP   = '10.x.xxx.xxx'
PORT_NUMBER = 2000
SIZE = 1024
print ("Test client sending packets to IP {0}, via port {1}\n".format(SERVER_IP, PORT_NUMBER))

myMessage1 = input(' Please enter your login name: ')

mySocket = socket( AF_INET, SOCK_DGRAM )
mySocket.sendto(myMessage1.encode('ascii'),(SERVER_IP,PORT_NUMBER))


# Receive result from server ?
(data,addr) = mySocket.recvfrom(SIZE)
print (result.decode())

sys.exit()

server2.py

    import subprocess

    import os
    from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM
    import sys

    PORT_NUMBER = 2000
    SIZE = 1024

    hostName = gethostbyname( '0.0.0.0' )

    mySocket = socket( AF_INET, SOCK_DGRAM )
    mySocket.bind( (hostName, PORT_NUMBER) )

    print ("Test server listening on port {0}\n".format(PORT_NUMBER))

    # Receive no more than 1024 bytes


    while True:
        (data,addr) = mySocket.recvfrom(SIZE)
        print (data.decode())
        batcmd=('net user ' + data.decode() + ' /domain')
        result = os.system(batcmd)

        # send result back to client ?
        mySocket.send(result.encode('ascii'))
        sys.exit()

关于我如何正确地做到这一点的任何建议?

1 个答案:

答案 0 :(得分:0)

简短回答,您通过无连接数据报套接字(UDP)发送信息。这就是你服务器无法回复的原因 - 它没有任何回传方式。

您可能应该使用流套接字(TCP)在两个进程之间创建连接。

或者,您可以对数据报套接字进行硬编码,以便在客户端进行监听。你的服务器神奇地“知道”哪个套接字并盲目地将答案发送到该套接字。 (不要这样做)......这就是我们发明TCP的原因。