python 使用socket远程发送命令并获得执行结果
#socket_server.py import socket import os import sys def work(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('0.0.0.0',1000)) sock.listen(5) while True: try: conn, addr = sock.accept() ret = conn.recv(2048) result = os.popen(ret).read() conn.send(result) except KeyboardInterrupt: print 'Now we will exit' sys.exit(0) sock.close() if __name__ == '__main__': work()
socket实例化,并且绑定1000端口,持续进行监听,’0.0.0.0’表示监听本地。sock.listen(backlog)表示可同时监听连接的数量,一般为5。sock.accept()返回(connection,address),connection通常用来发送和接收数据,address是客户端的Internet地址。conn.recv(2048)进行接收数据,然后conn.send(result)将结果送回给客户端。
#socket_client.py import socket def socket_send(command): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('192.168.1.55', 1000)) sock.send(command) result = sock.recv(2048) sock.close() return result if __name__ == '__main__': print socket_send('ls') sock.connect(address),里面是一个tuple,IP地址和PORT,发送命令给server,然后用result接收结果并进行return