-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathshellshare
174 lines (146 loc) · 5.24 KB
/
shellshare
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python
from __future__ import print_function
import argparse
import base64
import errno
import json
import os
import platform
import random
import socket
import string
import subprocess
import sys
import tempfile
import time
import uuid
try:
import httplib
except ImportError:
import http.client as httplib
try:
import thread
except ImportError:
import _thread as thread
try:
from urllib2 import quote as urllib_quote
except ImportError:
from urllib.parse import quote as urllib_quote
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
class NotAuthorizedException(Exception):
pass
class RequestTooLargeException(Exception):
pass
def id_generator(size=18, chars=string.ascii_letters + string.digits):
return ''.join(random.choice(chars) for x in range(size))
def terminal_size():
cols = subprocess.Popen('tput cols', shell=True, stdout=subprocess.PIPE)
rows = subprocess.Popen('tput lines', shell=True, stdout=subprocess.PIPE)
cols = int(cols.stdout.read().strip())
rows = int(rows.stdout.read().strip())
return {'cols': cols, 'rows': rows}
def post(conn, url, message, room, password):
is_successful = lambda status: status >= 200 and status < 300
headers = {'Content-type': 'application/json',
'Authorization': password}
data = json.dumps({'message': message, 'size': terminal_size()})
try:
conn.request('POST', '/%s' % room, data, headers)
res = conn.getresponse()
res.read()
if res.status == 401:
raise NotAuthorizedException()
elif res.status == 413:
raise RequestTooLargeException()
else:
return is_successful(res.status)
except httplib.HTTPException:
pass
except socket.error as e:
if e.errno != errno.ECONNREFUSED:
raise e
def stream_file(path, url, room, password):
retries = 3
try:
conn = create_connection(url)
f = open(path, 'rb')
success = True
while success:
time.sleep(1)
# osx wants this because EOF is cached
f.seek(0, os.SEEK_CUR)
data = f.read(4096)
if not (data == ""):
urlencoded = urllib_quote(data).encode('utf-8')
encoded_str = base64.b64encode(urlencoded).decode('utf-8')
for _ in range(retries):
success = post(conn, url, encoded_str, room, password)
if success:
break
else:
time.sleep(1)
conn = create_connection(url)
error('There was an error connecting to the server.')
except NotAuthorizedException:
error('You\'re not authorized to share on %s/%s.' % (url, room))
except RequestTooLargeException:
error('You\'ve wrote too much too fast. Please, slow down.')
def create_connection(url):
parsed_url = urlparse(url)
host = parsed_url.netloc
if parsed_url.scheme.lower() == 'https':
return httplib.HTTPSConnection(host)
else:
return httplib.HTTPConnection(host)
def error(*args):
print('\r\nERROR:', *args, file=sys.stderr)
print('\rERROR: Exit shellshare and try again later.', file=sys.stderr)
def delete(url, room, password):
headers = {'Authorization': password}
try:
conn = create_connection(url)
conn.request('DELETE', '/%s' % room, {}, headers)
res = conn.getresponse()
res.read()
except Exception:
pass
def parse_args():
description = 'Transmits the current shell to shellshare'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('-v', '--version', action='version',
version='%(prog)s 1.0.4')
parser.add_argument('-s', '--server', dest='server',
help=('shellshare instance URL'
' (default: https://shellshare.net)'),
default='https://shellshare.net')
parser.add_argument('-r', '--room', dest='room',
help='room to share into (default: random room)',
default=id_generator())
parser.add_argument('-p', '--password', dest='password',
help='room\'s broadcasting password (default: network card\'s MAC address)',
default=uuid.getnode())
args = parser.parse_args()
if not urlparse(args.server).scheme:
args.server = 'http://' + args.server
return args
args = parse_args()
room = 'r/%s' % args.room
tmp = tempfile.NamedTemporaryFile()
if platform.system() == 'Darwin':
shell_args = '-qt 0'
else:
shell_args = '-qf'
size = terminal_size()
if (size['rows'] > 30 or size['cols'] > 160):
print('Current terminal size is %dx%d.' % (size['rows'], size['cols']))
print('It\'s too big to be viewed on smaller screens.')
print('You can resize it anytime.')
print('Sharing terminal in %s/%s' % (args.server, room))
thread.start_new_thread(stream_file,
(tmp.name, args.server, room, args.password))
subprocess.call('script %s %s' % (shell_args, tmp.name), shell=True)
delete(args.server, room, args.password)
print('End of transmission.')