11import requests
22import subprocess
3+ import re
4+
5+ def is_valid_hostname (hostname ):
6+ """Validate hostname using regex pattern."""
7+ pattern = r'^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$'
8+ return bool (re .match (pattern , hostname ))
39
410def func_calls ():
511 formats .get_format ()
@@ -18,9 +24,30 @@ def func_calls():
1824 prep = req .prepare ()
1925 session .rebuild_proxies (prep , proxies )
2026
21- # Introduce a command injection vulnerability
22- user_input = input ("Enter a command to execute: " )
23- command = "ping " + user_input
24- subprocess .call (command , shell = True )
27+ def execute_ping (hostname ):
28+ """Execute ping command safely with input validation."""
29+ try :
30+ if not is_valid_hostname (hostname ):
31+ raise ValueError ("Invalid hostname format" )
32+
33+ command = ["ping" , hostname ]
34+ result = subprocess .run (command , check = True , capture_output = True , text = True )
35+ return result .stdout
36+ except ValueError as e :
37+ raise
38+ except subprocess .CalledProcessError as e :
39+ raise
40+ except Exception as e :
41+ raise
2542
26- print ("Command executed!" )
43+ if __name__ == '__main__' :
44+ try :
45+ user_input = input ("Enter hostname to ping: " )
46+ output = execute_ping (user_input )
47+ print (output )
48+ except ValueError as e :
49+ print (f"Error: { e } " )
50+ except subprocess .CalledProcessError as e :
51+ print (f"Command failed with exit code { e .returncode } " )
52+ except Exception as e :
53+ print (f"An unexpected error occurred: { e } " )
0 commit comments