forked from mahdi161/sshpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsshserver.py
89 lines (76 loc) · 2.27 KB
/
sshserver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python
import paramiko
import getopt
import threading
import sys
import socket
import subprocess
import getpass
import traceback
from paramiko.py3compat import input
host_key = paramiko.RSAKey(filename='test_rsa.key')
username = ''
passwd = ''
if username == '':
default_username = getpass.getuser()
username = input('username [%s]: ' % default_username)
if len(username) == 0:
username = default_username
if passwd == '':
passwd = input('Password:')
class Server(paramiko.ServerInterface):
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 == username) and (password == passwd):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
def main():
if not len(sys.argv[1:]):
print "Usage: ssh_server.py <server> <port>"
sys.exit(0)
server = sys.argv[1]
ssh_port = int(sys.argv[2])
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((server, ssh_port))
sock.listen(100)
print('Listening for connection ...')
client, addr = sock.accept()
except Exception as e:
print('*** Listen/accept failed: ' + str(e))
sys.exit(1)
print('Got a connection!')
try:
t = paramiko.Transport(client)
t.add_server_key(host_key)
paramiko.util.log_to_file("sshserver.log")
server = Server()
try:
t.start_server(server=server)
except paramiko.SSHException:
print('SSH negotiation failed')
sys.exit(1)
chan = t.accept(20)
chan.send("Connected...")
while 1:
command = chan.recv(4096)
try:
cmd_output = subprocess.check_output(command, shell=True)
chan.send(cmd_output)
except KeyboardInterrupt:
chan.close()
except Exception, e:
print "Exit: " + str(e)
try:
chan.close()
except:
pass
sys.exit(1)
if __name__ == '__main__':
main()