Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
77 lines (62 loc) · 2.14 KB
/
Copy pathcli.py
File metadata and controls
77 lines (62 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#
# @author Zac Dreyer
# @license LICENSE
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import shlex
import subprocess
from config_loader import load_config
config = load_config()
DISALLOWED_TOKENS = {';', '|', '&', '>', '<', '`', '$'}
MAX_COMMAND_LENGTH = 2048
def execute_stream(cmd, chunk_size=1024):
if not cmd or not cmd.strip():
raise ValueError('Command cannot be empty')
cleaned_cmd = cmd.strip()
if len(cleaned_cmd) > MAX_COMMAND_LENGTH:
raise ValueError('Command exceeds maximum length')
if any(ord(char) < 32 for char in cleaned_cmd):
raise ValueError('Command contains control characters')
try:
argv = shlex.split(cleaned_cmd, posix=True)
except ValueError as exc:
raise ValueError('Command contains invalid quoting') from exc
if not argv:
raise ValueError('Command cannot be empty')
if any(token in DISALLOWED_TOKENS or any(char in token for char in DISALLOWED_TOKENS) for token in argv):
raise ValueError('Command contains disallowed shell metacharacters')
env = os.environ.copy()
env['PYTHONUNBUFFERED'] = '1'
process = subprocess.Popen(
argv,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1,
text=True,
encoding='utf-8',
errors='replace',
env=env
)
try:
while True:
chunk = process.stdout.read(chunk_size)
if not chunk:
break
yield chunk
process.wait()
finally:
if process.stdout:
process.stdout.close()
def execute(cmd):
output = ''.join(execute_stream(cmd))
if config.app['debug'] == 1:
print(output)
return output