0

I want to execute multiple shell commands one after another. The commands are received from a remote device through socket. What i need to do is to create a shell that is accessible remotely. With subprocess.Popen i am able to execute commands and get output. But if i want to execute cd MyDIR and then ls -l. If I execute it as 2 lines of code, i get file listing of the parent directory rather than the the directory i cd into. Using cd MyDIR && ls -l gives the required result. If i use the communicate method, i am not getting any result and also the stdin gets closed. Can someone help me with a piece of code?

Edit

The solution given here Interacting with bash from python doesn't solve my problem as i want to keep the shell active as long as possible and as much as needed. Trying the solution on that pages gives a message that IO operation on closed file.

5
  • Possible duplicate of Interacting with bash from python Commented Jan 13, 2017 at 13:57
  • @PatrickHaugh Yes it looks like a duplicate but i want to solve the IO operation on closed file error. I want to keep the communication active. Commented Jan 13, 2017 at 14:12
  • Looks like it can be done easier if you'll listen with bash. Just nc -k -l 4444 | bash. Commented Jan 13, 2017 at 15:05
  • @Raz I cant listen with nc -k -l 4444 | bash Because, bash is only a part of what i want to do. I am actually trying to run shell commands using Telegram bot. I will remotely send the command and bot executes it on my RPI and it will send me back the response. This is what i actually need. Commented Jan 13, 2017 at 16:44
  • May be you can start tmux session and interact with it. Check this lib. It can connect to session and do pane.send_keys('echo hey send now'). Commented Jan 13, 2017 at 16:50

1 Answer 1

1

This code helps

from subprocess import Popen, PIPE
from time import sleep
from fcntl import fcntl, F_GETFL, F_SETFL
from os import O_NONBLOCK, read

# run the shell as a subprocess:
p = Popen(['python', 'shell.py'],
        stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = False)
# set the O_NONBLOCK flag of p.stdout file descriptor:
flags = fcntl(p.stdout, F_GETFL) # get current p.stdout flags
fcntl(p.stdout, F_SETFL, flags | O_NONBLOCK)
# issue command:
p.stdin.write('command\n')
# let the shell output the result:
sleep(0.1)
# get the output
while True:
    try:
        print read(p.stdout.fileno(), 1024),
    except OSError:
        # the os throws an exception if there is no data
        print '[No more data]'
        break

Here is the source http://eyalarubas.com/python-subproc-nonblock.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.