简体   繁体   中英

Using data received from TCP socket [ python ]

So, I am trying to pass parameters to a bash shell script across a python TCP socket connection. The script being executed in the bash shell always bombs out even though when I print the variable being passed to os.system() or subprocess.call() it looks correct. Any ideas? Small chunk of the code that is giving me issues.

while 1:
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])    
    data = conn.recv(1024)
    if not data:
        break
    data2 = data.rstrip('\n')
    cmd = 'ls ' + data2
    #os.system(cmd)  
    subprocess.call([cmd], shell=True)
    print cmd

Python's subprocess call ( doc ) takes a single string to execute or a list of arguments. You're passing a string as a single argument and thus the entire thing is interpreted as the command to execute, which of course cannot be found.

subprocess.call(cmd, shell=True) or subprocess.call(['ls', data2])

The latter is preferred as it means a malicious caller cannot create arbitrary shell actions by passing "foo; rm -rf / &" down the socket.

Note: Better to use call(('ls', data2)) (parentheses instead of brackets) to create a simple Python "tuple" rather than a dynamic list for passing to call(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM