97 lines
2.4 KiB
Python
97 lines
2.4 KiB
Python
# modified from https://github.com/paramiko/paramiko/blob/main/demos/interactive.py
|
|
|
|
import socket
|
|
import sys
|
|
from paramiko.py3compat import u
|
|
|
|
# windows does not have termios...
|
|
try:
|
|
import termios
|
|
import tty
|
|
|
|
has_termios = True
|
|
except ImportError:
|
|
has_termios = False
|
|
|
|
|
|
def interactive_shell(chan):
|
|
if has_termios:
|
|
posix_shell(chan)
|
|
else:
|
|
windows_shell(chan)
|
|
|
|
|
|
def posix_shell(chan):
|
|
import select
|
|
|
|
oldtty = termios.tcgetattr(sys.stdin)
|
|
try:
|
|
tty.setraw(sys.stdin.fileno())
|
|
tty.setcbreak(sys.stdin.fileno())
|
|
chan.settimeout(0.0)
|
|
|
|
while True:
|
|
r, w, e = select.select([chan, sys.stdin], [], [])
|
|
if chan in r:
|
|
try:
|
|
x = u(chan.recv(1024))
|
|
if len(x) == 0:
|
|
sys.stdout.write("\r\n*** EOF\r\n")
|
|
break
|
|
sys.stdout.write(x)
|
|
sys.stdout.flush()
|
|
except socket.timeout:
|
|
pass
|
|
if sys.stdin in r:
|
|
x = sys.stdin.read(1)
|
|
if len(x) == 0:
|
|
break
|
|
chan.send(x)
|
|
|
|
finally:
|
|
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
|
|
|
|
|
|
# thanks to Mike Looijmans for this code
|
|
def windows_shell(chan):
|
|
import threading
|
|
|
|
sys.stdout.write(
|
|
"Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n"
|
|
)
|
|
global cmdout
|
|
def writeall(sock):
|
|
global cmdout
|
|
line = 0
|
|
while True:
|
|
data = sock.recv(256)
|
|
if not data:
|
|
sys.exit(0)
|
|
cmdout = data.decode("utf-8")
|
|
if "]$" in data.decode("utf-8"):
|
|
line += 1
|
|
if line > 1:
|
|
sys.stdout.write("press ENTER to continue\n")
|
|
sys.stdout.write(cmdout)
|
|
sys.stdout.flush()
|
|
|
|
|
|
writer = threading.Thread(target=writeall, args=(chan,))
|
|
writer.start()
|
|
|
|
try:
|
|
chan.send("/homes/hyu3/anaconda3/envs/Documents/bin/python /homes/hyu3/Documents/dummy.py\n")
|
|
# chan.send("vncpasswd\n")
|
|
while True:
|
|
if "]$" in cmdout:
|
|
chan.send("exit\n")
|
|
break
|
|
d = sys.stdin.read(1)
|
|
if not d:
|
|
break
|
|
chan.send(d)
|
|
except (EOFError, OSError):
|
|
# user hit ^Z or F6
|
|
pass
|
|
|