Python通过套接字发送命令 [英] Python sending command over a socket
问题描述
我有点麻烦.我想创建一个简单的程序,该程序连接到服务器并使用子进程执行命令,然后将结果返回给客户端.很简单,但我无法正常工作.现在,这就是我所拥有的: 客户:
I'm having a bit of trouble. I want to create a simple program that connects to the server and executes a command using subprocess then returns the result to the client. It's simple but I can't get it to work. Right now this is what I have: client:
import sys, socket, subprocess
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = sys.argv[1]
port = int(sys.argv[2])
socksize = 1024
conn.connect((host, port))
while True:
shell = raw_input("$ ")
conn.send(shell)
data = conn.recv(socksize)
#msglen = len(data)
output = data
iotype = subprocess.PIPE
cmd = ['/bin/sh', '-c', shell]
proc = subprocess.Popen(cmd, stdout=iotype).wait()
stdout,stderr = proc.communicate()
conn.send(stdout)
print(output)
if proc.returncode != 0:
print("Error")
服务器:
import sys, socket, subprocess
host = ''
port = 50106
socksize = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: %s" %port)
s.listen(1)
print("Now listening...\n")
conn, addr = s.accept()
while True:
print 'New connection from %s:%d' % (addr[0], addr[1])
data = conn.recv(socksize)
cmd = ['/bin/sh', '-c', data]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE).wait()
stdout,stderr = cmd.communicate()
if not data:
break
elif data == 'killsrv':
sys.exit()
推荐答案
危险,威尔·罗宾逊!!!
Danger, Will Robinson!!!
您真的要通过网络以明文形式发送命令而不进行身份验证吗?这是非常非常危险的.
Do you really want to send commands in clear text without authentication over the network? It is very, very dangerous.
使用 paramiko 通过SSH进行.
好的,我已经多次听到这个答案了.我不想使用SSH,我只是在构建它以了解有关套接字的更多信息.如果我想向系统发送命令,我将不会实际使用它. – AustinM
Alright I've heard this answer too many times. I don't want to use SSH I'm just building it to learn more about sockets. I'm not going to actually use this if I want to send commands to a system. – AustinM
我无法从您的问题中推断出这一崇高的追求. :-)
There is no way I could infer this noble quest from your question. :-)
套接字模块是posix库上的一薄层;普通的套接字很乏味,而且很难正确设置.截止到今天(2014年),异步I/O和并发并不是Python的最强特性-3.4开始有所改变,但是库将滞后一段时间.我的建议是花时间学习一些更高级的API,例如Twisted( twistedmatrix.com/trac ).如果您真的对低级内容感兴趣,请深入研究项目源代码.
The sockets module is a thin layer over the posix library; plain sockets is tedious and hard to get right. As of today (2014), asynchronous I/O and concurrency are not among Python's strongest traits - 3.4 is starting to change that but libraries will lag behind for a while. My advice is to spent your time learning some higher level API like Twisted (twistedmatrix.com/trac). If you are really interested in the low level stuff, dive in the project source.
好的.关于如何在这种类型的事情上使用扭曲的任何想法吗? – AustinM
Alright. Any idea on how I could use twisted for this type of thing? – AustinM
查看 twistedmatrix.com/documents/current/core/examples/#auto2
这篇关于Python通过套接字发送命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!