linux - write commands from one terminal to another

user1364700 picture user1364700 · Apr 29, 2012 · Viewed 15.2k times · Source

I need to write commands from one terminal to another terminal.

I tried these:

echo -e "ls\n" > /proc/pid/fd/0
echo -e "ls\n" > /dev/pts/4

Which just prints the ls as output and doesn't execute.

I tried these:

chmod 777 /dev/tty4 ;echo "ls" > /dev/tty4
chmod 777 /dev/tty40 ;echo "ls" > /dev/tty40

Which don't seem to do anything

Any ideas?

[note that I don't want to touch the second terminal to accomplish this. only the first one]

Answer

esoriano picture esoriano · Dec 4, 2013

Python code:

#!/usr/bin/python

import sys,os,fcntl,termios
if len(sys.argv) != 3:
   sys.stderr.write("usage: ttyexec.py tty command\n")
   sys.exit(1)
fd = os.open("/dev/" + sys.argv[1], os.O_RDWR)
cmd=sys.argv[2]
for i in range(len(cmd)):
   fcntl.ioctl(fd, termios.TIOCSTI, cmd[i])
fcntl.ioctl(fd, termios.TIOCSTI, '\n')
os.close(fd)