use paramiko create a simple ssh server in win7
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 9.9k
- Forks
- 2.1k
- PR merge metrics
- No merged PRs in 30d
Description
I use the paramiko to create a simple ssh server in win7, just wanna execute command in win7 when a client connected.
#!/usr/bin/env python
#coding : utf-8
import base64
from binascii import hexlify
import os
import socket
import sys
import threading
import traceback
import paramiko
from paramiko.py3compat import b, u, decodebytes
#setup logging
paramiko.util.log_to_file("demo_server.log")
host_key = paramiko.RSAKey(filename="",password='')
#host_key = paramiko.DSSKey(filename='test_dss.key')
#print("Read key: " + u(hexlify(host_key.get_fingerprint())))
class Server(paramiko.ServerInterface):
with open('test.pub','r') as f :
good_pub_key=str(f.readlines())
def __init__(self):
self.event = threading.Event()
def check_channel_request(self, kind, chanid):
if kind == "session":
return paramiko.OPEN_SUCCEEDED
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_auth_password(self, username, password):
if (username == "******") and (password == "******"):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
def check_auth_publickey(self, username, key):
print("Auth attempt with key: " + u(hexlify(key.get_fingerprint())))
if (username == "root") and (key == self.good_pub_key):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
def check_auth_gssapi_with_mic(
self, username, gss_authenticated=paramiko.AUTH_FAILED, cc_file=None
):
if gss_authenticated == paramiko.AUTH_SUCCESSFUL:
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
def check_auth_gssapi_keyex(
self, username, gss_authenticated=paramiko.AUTH_FAILED, cc_file=None
):
if gss_authenticated == paramiko.AUTH_SUCCESSFUL:
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
def enable_auth_gssapi(self):
return True
def get_allowed_auths(self, username):
return "gssapi-keyex,gssapi-with-mic,password,publickey"
def check_channel_shell_request(self, channel):
self.event.set()
return True
def check_channel_pty_request(
self, channel, term, width, height, pixelwidth, pixelheight, modes
):
return True
def windows_shell(chan):
import threading
import subprocess
sys.stdout.write(
"terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n"
)
def writeall(sock):
#sock.send(('ssh > $:').encode('utf-8'))
while True:
sock.send(('ssh > $:').encode('utf-8'))
data = sock.recv(1024).decode()
if not data and data == 'exit':
break
try:
output=subprocess.check_output(data,shell=True,stderr=subprocess.STDOUT)
sock.send(output)
except Exception as e:
sock.send('execute error!\r\n')
sock.close()
writer = threading.Thread(target=writeall, args=(chan,))
writer.start()
writer.join()
#writeall(sock)
DoGSSAPIKeyExchange = False
#now connect
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("", 22))
except Exception as e:
print("*** Bind failed: " + str(e))
traceback.print_exc()
sys.exit(1)
try:
sock.listen(100)
print("Listening for connection ...")
client, addr = sock.accept()
except Exception as e:
print("*** Listen/accept failed: " + str(e))
traceback.print_exc()
sys.exit(1)
print("Got a connection!")
try:
t = paramiko.Transport(client, gss_kex=DoGSSAPIKeyExchange)
t.set_gss_host(socket.getfqdn(""))
try:
t.load_server_moduli()
except:
print("(Failed to load moduli -- gex will be unsupported.)")
raise
t.add_server_key(host_key)
server = Server()
try:
t.start_server(server=server)
except paramiko.SSHException:
print("*** SSH negotiation failed.")
sys.exit(1)
#wait for auth
chan = t.accept(200)
if chan is None:
print("*** No channel.")
sys.exit(1)
print("Authenticated!")
windows_shell(chan)
t.close()
sys.exit(0)
except Exception as e:
print("*** Caught exception: " + str(e.class) + ": " + str(e))
traceback.print_exc()
try:
t.close()
except:
pass
sys.exit(1)
I use a subprocess.check_out to get a shell in win7, but when i use linux to connect the ssh server, the command is ssh *******@win7'ip , auth successful and connected. but when i enter the command in the linux, I just can enter a character . This is the first question
another question is i cannot use the putty in win7 to connect the ssh server in win7 . I donot know why
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the supplied server and reading the windows_shell loop, especially its subprocess.check_output call, then trace the Transport.start_server and channel-handling entry points. Compare the Linux SSH and PuTTY connection paths. Done means identifying the cause of the single-character input behavior and the failed PuTTY connection, with both cases reproducibly addressed.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- networking
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100