popen
call with shell equals True
BAN-B602 75
76 return subprocess.check_output(
77 f"ip route | grep default | grep {iface} | cut -d' ' -f3",
78 shell=True, 79 encoding='utf-8' 80 ) 81
82
83def ifconfig_get_up(iface):
55 try:
56 inet_line = subprocess.check_output(
57 f"ip -6 addr show {iface} | grep 'inet6 '",
58 shell=True, 59 encoding='utf-8' 60 ) 61 return inet_line.strip().split()[1].split('/')
62 except subprocess.CalledProcessError as e:
63 # No ipv6 found
34 try:
35 inet_line = subprocess.check_output(
36 f"ip -4 addr show {iface} | grep 'inet '",
37 shell=True, 38 encoding='utf-8' 39 ) 40 return inet_line.strip().split()[1].split('/')
41 except subprocess.CalledProcessError as e:
42 # No ipv4 found
Using shell=True
can expose you to security risks if someone crafts input to issue different commands than the ones you intended.
Python possesses many mechanisms to invoke an external executable. However, doing so may present a security issue if appropriate care is not taken to sanitize any user-provided or variable input. Subprocess invocation using a command shell is dangerous as it is vulnerable to various shell injection attacks. It is possible for an attacker to craft inputs to issue different commands than the ones you intended, for example: removing a file.
Great care should be taken to sanitize all input in order to mitigate this risk. Calls of this type are identified by a parameter of shell=True
being given.
It is recommended to use functions that don't spawn a shell. If you must use them, use shlex.quote
to sanitize the input.
import subprocess
subprocess.Popen(cmd, shell=True) # Sensitive, shell spawned
import subprocess
subprocess.Popen(cmd)