Created
December 12, 2017 08:28
-
-
Save ficapy/e231b563ee6362b548c9290411813fb2 to your computer and use it in GitHub Desktop.
paramiko_with_tty demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# Author: ficapy | |
# Create: '12/12/2017' | |
import os | |
import threading | |
from paramiko import SSHConfig, SSHClient, AutoAddPolicy | |
HOSTNAME = 'aliyun' | |
config = SSHConfig() | |
config.parse(open(os.path.expanduser('~/.ssh/config'))) | |
server_config = config.lookup(HOSTNAME) | |
user, hostname, port, keys = ( | |
server_config.get('user'), | |
server_config.get('hostname'), | |
server_config.get('port'), | |
server_config.get('identityfile') | |
) | |
client = SSHClient() | |
client.set_missing_host_key_policy(AutoAddPolicy()) | |
client.connect(hostname=hostname, username=user, port=port, key_filename=keys) | |
channel = client.invoke_shell() | |
# 和 client.exec_command 不相同 | |
def handle_output(): | |
while True: | |
if channel != None and channel.recv_ready(): | |
data = channel.recv(1024) | |
while channel.recv_ready(): | |
data += channel.recv(1024) | |
strdata = str(data, "utf8") | |
strdata.replace('\r', '') | |
print(strdata, end="") | |
if (strdata.endswith("$ ")): | |
print("\n$ ", end="") | |
thread = threading.Thread(target=handle_output) | |
thread.daemon = True | |
thread.start() | |
while True: | |
command = input('$ ') | |
if command.startswith(" "): | |
command = command[1:] | |
channel.send(command + "\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment