tkconch.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. # -*- test-case-name: twisted.conch.test.test_scripts -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Implementation module for the `tkconch` command.
  6. """
  7. from __future__ import print_function
  8. from twisted.conch import error
  9. from twisted.conch.ui import tkvt100
  10. from twisted.conch.ssh import transport, userauth, connection, common, keys
  11. from twisted.conch.ssh import session, forwarding, channel
  12. from twisted.conch.client.default import isInKnownHosts
  13. from twisted.internet import reactor, defer, protocol, tksupport
  14. from twisted.python import usage, log
  15. from twisted.python.compat import _PY3
  16. import os, sys, getpass, struct, base64, signal
  17. if _PY3:
  18. import tkinter as Tkinter
  19. import tkinter.filedialog as tkFileDialog
  20. import tkinter.messagebox as tkMessageBox
  21. else:
  22. import Tkinter, tkFileDialog, tkMessageBox
  23. class TkConchMenu(Tkinter.Frame):
  24. def __init__(self, *args, **params):
  25. ## Standard heading: initialization
  26. Tkinter.Frame.__init__(self, *args, **params)
  27. self.master.title('TkConch')
  28. self.localRemoteVar = Tkinter.StringVar()
  29. self.localRemoteVar.set('local')
  30. Tkinter.Label(self, anchor='w', justify='left', text='Hostname').grid(column=1, row=1, sticky='w')
  31. self.host = Tkinter.Entry(self)
  32. self.host.grid(column=2, columnspan=2, row=1, sticky='nesw')
  33. Tkinter.Label(self, anchor='w', justify='left', text='Port').grid(column=1, row=2, sticky='w')
  34. self.port = Tkinter.Entry(self)
  35. self.port.grid(column=2, columnspan=2, row=2, sticky='nesw')
  36. Tkinter.Label(self, anchor='w', justify='left', text='Username').grid(column=1, row=3, sticky='w')
  37. self.user = Tkinter.Entry(self)
  38. self.user.grid(column=2, columnspan=2, row=3, sticky='nesw')
  39. Tkinter.Label(self, anchor='w', justify='left', text='Command').grid(column=1, row=4, sticky='w')
  40. self.command = Tkinter.Entry(self)
  41. self.command.grid(column=2, columnspan=2, row=4, sticky='nesw')
  42. Tkinter.Label(self, anchor='w', justify='left', text='Identity').grid(column=1, row=5, sticky='w')
  43. self.identity = Tkinter.Entry(self)
  44. self.identity.grid(column=2, row=5, sticky='nesw')
  45. Tkinter.Button(self, command=self.getIdentityFile, text='Browse').grid(column=3, row=5, sticky='nesw')
  46. Tkinter.Label(self, text='Port Forwarding').grid(column=1, row=6, sticky='w')
  47. self.forwards = Tkinter.Listbox(self, height=0, width=0)
  48. self.forwards.grid(column=2, columnspan=2, row=6, sticky='nesw')
  49. Tkinter.Button(self, text='Add', command=self.addForward).grid(column=1, row=7)
  50. Tkinter.Button(self, text='Remove', command=self.removeForward).grid(column=1, row=8)
  51. self.forwardPort = Tkinter.Entry(self)
  52. self.forwardPort.grid(column=2, row=7, sticky='nesw')
  53. Tkinter.Label(self, text='Port').grid(column=3, row=7, sticky='nesw')
  54. self.forwardHost = Tkinter.Entry(self)
  55. self.forwardHost.grid(column=2, row=8, sticky='nesw')
  56. Tkinter.Label(self, text='Host').grid(column=3, row=8, sticky='nesw')
  57. self.localForward = Tkinter.Radiobutton(self, text='Local', variable=self.localRemoteVar, value='local')
  58. self.localForward.grid(column=2, row=9)
  59. self.remoteForward = Tkinter.Radiobutton(self, text='Remote', variable=self.localRemoteVar, value='remote')
  60. self.remoteForward.grid(column=3, row=9)
  61. Tkinter.Label(self, text='Advanced Options').grid(column=1, columnspan=3, row=10, sticky='nesw')
  62. Tkinter.Label(self, anchor='w', justify='left', text='Cipher').grid(column=1, row=11, sticky='w')
  63. self.cipher = Tkinter.Entry(self, name='cipher')
  64. self.cipher.grid(column=2, columnspan=2, row=11, sticky='nesw')
  65. Tkinter.Label(self, anchor='w', justify='left', text='MAC').grid(column=1, row=12, sticky='w')
  66. self.mac = Tkinter.Entry(self, name='mac')
  67. self.mac.grid(column=2, columnspan=2, row=12, sticky='nesw')
  68. Tkinter.Label(self, anchor='w', justify='left', text='Escape Char').grid(column=1, row=13, sticky='w')
  69. self.escape = Tkinter.Entry(self, name='escape')
  70. self.escape.grid(column=2, columnspan=2, row=13, sticky='nesw')
  71. Tkinter.Button(self, text='Connect!', command=self.doConnect).grid(column=1, columnspan=3, row=14, sticky='nesw')
  72. # Resize behavior(s)
  73. self.grid_rowconfigure(6, weight=1, minsize=64)
  74. self.grid_columnconfigure(2, weight=1, minsize=2)
  75. self.master.protocol("WM_DELETE_WINDOW", sys.exit)
  76. def getIdentityFile(self):
  77. r = tkFileDialog.askopenfilename()
  78. if r:
  79. self.identity.delete(0, Tkinter.END)
  80. self.identity.insert(Tkinter.END, r)
  81. def addForward(self):
  82. port = self.forwardPort.get()
  83. self.forwardPort.delete(0, Tkinter.END)
  84. host = self.forwardHost.get()
  85. self.forwardHost.delete(0, Tkinter.END)
  86. if self.localRemoteVar.get() == 'local':
  87. self.forwards.insert(Tkinter.END, 'L:%s:%s' % (port, host))
  88. else:
  89. self.forwards.insert(Tkinter.END, 'R:%s:%s' % (port, host))
  90. def removeForward(self):
  91. cur = self.forwards.curselection()
  92. if cur:
  93. self.forwards.remove(cur[0])
  94. def doConnect(self):
  95. finished = 1
  96. options['host'] = self.host.get()
  97. options['port'] = self.port.get()
  98. options['user'] = self.user.get()
  99. options['command'] = self.command.get()
  100. cipher = self.cipher.get()
  101. mac = self.mac.get()
  102. escape = self.escape.get()
  103. if cipher:
  104. if cipher in SSHClientTransport.supportedCiphers:
  105. SSHClientTransport.supportedCiphers = [cipher]
  106. else:
  107. tkMessageBox.showerror('TkConch', 'Bad cipher.')
  108. finished = 0
  109. if mac:
  110. if mac in SSHClientTransport.supportedMACs:
  111. SSHClientTransport.supportedMACs = [mac]
  112. elif finished:
  113. tkMessageBox.showerror('TkConch', 'Bad MAC.')
  114. finished = 0
  115. if escape:
  116. if escape == 'none':
  117. options['escape'] = None
  118. elif escape[0] == '^' and len(escape) == 2:
  119. options['escape'] = chr(ord(escape[1])-64)
  120. elif len(escape) == 1:
  121. options['escape'] = escape
  122. elif finished:
  123. tkMessageBox.showerror('TkConch', "Bad escape character '%s'." % escape)
  124. finished = 0
  125. if self.identity.get():
  126. options.identitys.append(self.identity.get())
  127. for line in self.forwards.get(0,Tkinter.END):
  128. if line[0]=='L':
  129. options.opt_localforward(line[2:])
  130. else:
  131. options.opt_remoteforward(line[2:])
  132. if '@' in options['host']:
  133. options['user'], options['host'] = options['host'].split('@',1)
  134. if (not options['host'] or not options['user']) and finished:
  135. tkMessageBox.showerror('TkConch', 'Missing host or username.')
  136. finished = 0
  137. if finished:
  138. self.master.quit()
  139. self.master.destroy()
  140. if options['log']:
  141. realout = sys.stdout
  142. log.startLogging(sys.stderr)
  143. sys.stdout = realout
  144. else:
  145. log.discardLogs()
  146. log.deferr = handleError # HACK
  147. if not options.identitys:
  148. options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa']
  149. host = options['host']
  150. port = int(options['port'] or 22)
  151. log.msg((host,port))
  152. reactor.connectTCP(host, port, SSHClientFactory())
  153. frame.master.deiconify()
  154. frame.master.title('%s@%s - TkConch' % (options['user'], options['host']))
  155. else:
  156. self.focus()
  157. class GeneralOptions(usage.Options):
  158. synopsis = """Usage: tkconch [options] host [command]
  159. """
  160. optParameters = [['user', 'l', None, 'Log in using this user name.'],
  161. ['identity', 'i', '~/.ssh/identity', 'Identity for public key authentication'],
  162. ['escape', 'e', '~', "Set escape character; ``none'' = disable"],
  163. ['cipher', 'c', None, 'Select encryption algorithm.'],
  164. ['macs', 'm', None, 'Specify MAC algorithms for protocol version 2.'],
  165. ['port', 'p', None, 'Connect to this port. Server must be on the same port.'],
  166. ['localforward', 'L', None, 'listen-port:host:port Forward local port to remote address'],
  167. ['remoteforward', 'R', None, 'listen-port:host:port Forward remote port to local address'],
  168. ]
  169. optFlags = [['tty', 't', 'Tty; allocate a tty even if command is given.'],
  170. ['notty', 'T', 'Do not allocate a tty.'],
  171. ['version', 'V', 'Display version number only.'],
  172. ['compress', 'C', 'Enable compression.'],
  173. ['noshell', 'N', 'Do not execute a shell or command.'],
  174. ['subsystem', 's', 'Invoke command (mandatory) as SSH2 subsystem.'],
  175. ['log', 'v', 'Log to stderr'],
  176. ['ansilog', 'a', 'Print the received data to stdout']]
  177. _ciphers = transport.SSHClientTransport.supportedCiphers
  178. _macs = transport.SSHClientTransport.supportedMACs
  179. compData = usage.Completions(
  180. mutuallyExclusive=[("tty", "notty")],
  181. optActions={
  182. "cipher": usage.CompleteList(_ciphers),
  183. "macs": usage.CompleteList(_macs),
  184. "localforward": usage.Completer(descr="listen-port:host:port"),
  185. "remoteforward": usage.Completer(descr="listen-port:host:port")},
  186. extraActions=[usage.CompleteUserAtHost(),
  187. usage.Completer(descr="command"),
  188. usage.Completer(descr="argument", repeat=True)]
  189. )
  190. identitys = []
  191. localForwards = []
  192. remoteForwards = []
  193. def opt_identity(self, i):
  194. self.identitys.append(i)
  195. def opt_localforward(self, f):
  196. localPort, remoteHost, remotePort = f.split(':') # doesn't do v6 yet
  197. localPort = int(localPort)
  198. remotePort = int(remotePort)
  199. self.localForwards.append((localPort, (remoteHost, remotePort)))
  200. def opt_remoteforward(self, f):
  201. remotePort, connHost, connPort = f.split(':') # doesn't do v6 yet
  202. remotePort = int(remotePort)
  203. connPort = int(connPort)
  204. self.remoteForwards.append((remotePort, (connHost, connPort)))
  205. def opt_compress(self):
  206. SSHClientTransport.supportedCompressions[0:1] = ['zlib']
  207. def parseArgs(self, *args):
  208. if args:
  209. self['host'] = args[0]
  210. self['command'] = ' '.join(args[1:])
  211. else:
  212. self['host'] = ''
  213. self['command'] = ''
  214. # Rest of code in "run"
  215. options = None
  216. menu = None
  217. exitStatus = 0
  218. frame = None
  219. def deferredAskFrame(question, echo):
  220. if frame.callback:
  221. raise ValueError("can't ask 2 questions at once!")
  222. d = defer.Deferred()
  223. resp = []
  224. def gotChar(ch, resp=resp):
  225. if not ch: return
  226. if ch=='\x03': # C-c
  227. reactor.stop()
  228. if ch=='\r':
  229. frame.write('\r\n')
  230. stresp = ''.join(resp)
  231. del resp
  232. frame.callback = None
  233. d.callback(stresp)
  234. return
  235. elif 32 <= ord(ch) < 127:
  236. resp.append(ch)
  237. if echo:
  238. frame.write(ch)
  239. elif ord(ch) == 8 and resp: # BS
  240. if echo: frame.write('\x08 \x08')
  241. resp.pop()
  242. frame.callback = gotChar
  243. frame.write(question)
  244. frame.canvas.focus_force()
  245. return d
  246. def run():
  247. global menu, options, frame
  248. args = sys.argv[1:]
  249. if '-l' in args: # cvs is an idiot
  250. i = args.index('-l')
  251. args = args[i:i+2]+args
  252. del args[i+2:i+4]
  253. for arg in args[:]:
  254. try:
  255. i = args.index(arg)
  256. if arg[:2] == '-o' and args[i+1][0]!='-':
  257. args[i:i+2] = [] # suck on it scp
  258. except ValueError:
  259. pass
  260. root = Tkinter.Tk()
  261. root.withdraw()
  262. top = Tkinter.Toplevel()
  263. menu = TkConchMenu(top)
  264. menu.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
  265. options = GeneralOptions()
  266. try:
  267. options.parseOptions(args)
  268. except usage.UsageError as u:
  269. print('ERROR: %s' % u)
  270. options.opt_help()
  271. sys.exit(1)
  272. for k,v in options.items():
  273. if v and hasattr(menu, k):
  274. getattr(menu,k).insert(Tkinter.END, v)
  275. for (p, (rh, rp)) in options.localForwards:
  276. menu.forwards.insert(Tkinter.END, 'L:%s:%s:%s' % (p, rh, rp))
  277. options.localForwards = []
  278. for (p, (rh, rp)) in options.remoteForwards:
  279. menu.forwards.insert(Tkinter.END, 'R:%s:%s:%s' % (p, rh, rp))
  280. options.remoteForwards = []
  281. frame = tkvt100.VT100Frame(root, callback=None)
  282. root.geometry('%dx%d'%(tkvt100.fontWidth*frame.width+3, tkvt100.fontHeight*frame.height+3))
  283. frame.pack(side = Tkinter.TOP)
  284. tksupport.install(root)
  285. root.withdraw()
  286. if (options['host'] and options['user']) or '@' in options['host']:
  287. menu.doConnect()
  288. else:
  289. top.mainloop()
  290. reactor.run()
  291. sys.exit(exitStatus)
  292. def handleError():
  293. from twisted.python import failure
  294. global exitStatus
  295. exitStatus = 2
  296. log.err(failure.Failure())
  297. reactor.stop()
  298. raise
  299. class SSHClientFactory(protocol.ClientFactory):
  300. noisy = 1
  301. def stopFactory(self):
  302. reactor.stop()
  303. def buildProtocol(self, addr):
  304. return SSHClientTransport()
  305. def clientConnectionFailed(self, connector, reason):
  306. tkMessageBox.showwarning('TkConch','Connection Failed, Reason:\n %s: %s' % (reason.type, reason.value))
  307. class SSHClientTransport(transport.SSHClientTransport):
  308. def receiveError(self, code, desc):
  309. global exitStatus
  310. exitStatus = 'conch:\tRemote side disconnected with error code %i\nconch:\treason: %s' % (code, desc)
  311. def sendDisconnect(self, code, reason):
  312. global exitStatus
  313. exitStatus = 'conch:\tSending disconnect with error code %i\nconch:\treason: %s' % (code, reason)
  314. transport.SSHClientTransport.sendDisconnect(self, code, reason)
  315. def receiveDebug(self, alwaysDisplay, message, lang):
  316. global options
  317. if alwaysDisplay or options['log']:
  318. log.msg('Received Debug Message: %s' % message)
  319. def verifyHostKey(self, pubKey, fingerprint):
  320. #d = defer.Deferred()
  321. #d.addCallback(lambda x:defer.succeed(1))
  322. #d.callback(2)
  323. #return d
  324. goodKey = isInKnownHosts(options['host'], pubKey, {'known-hosts': None})
  325. if goodKey == 1: # good key
  326. return defer.succeed(1)
  327. elif goodKey == 2: # AAHHHHH changed
  328. return defer.fail(error.ConchError('bad host key'))
  329. else:
  330. if options['host'] == self.transport.getPeer().host:
  331. host = options['host']
  332. khHost = options['host']
  333. else:
  334. host = '%s (%s)' % (options['host'],
  335. self.transport.getPeer().host)
  336. khHost = '%s,%s' % (options['host'],
  337. self.transport.getPeer().host)
  338. keyType = common.getNS(pubKey)[0]
  339. ques = """The authenticity of host '%s' can't be established.\r
  340. %s key fingerprint is %s.""" % (host,
  341. {b'ssh-dss':'DSA', b'ssh-rsa':'RSA'}[keyType],
  342. fingerprint)
  343. ques+='\r\nAre you sure you want to continue connecting (yes/no)? '
  344. return deferredAskFrame(ques, 1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)
  345. def _cbVerifyHostKey(self, ans, pubKey, khHost, keyType):
  346. if ans.lower() not in ('yes', 'no'):
  347. return deferredAskFrame("Please type 'yes' or 'no': ",1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)
  348. if ans.lower() == 'no':
  349. frame.write('Host key verification failed.\r\n')
  350. raise error.ConchError('bad host key')
  351. try:
  352. frame.write(
  353. "Warning: Permanently added '%s' (%s) to the list of "
  354. "known hosts.\r\n" %
  355. (khHost, {b'ssh-dss':'DSA', b'ssh-rsa':'RSA'}[keyType]))
  356. with open(os.path.expanduser('~/.ssh/known_hosts'), 'a') as known_hosts:
  357. encodedKey = base64.encodestring(pubKey).replace(b'\n', b'')
  358. known_hosts.write('\n%s %s %s' % (khHost, keyType, encodedKey))
  359. except:
  360. log.deferr()
  361. raise error.ConchError
  362. def connectionSecure(self):
  363. if options['user']:
  364. user = options['user']
  365. else:
  366. user = getpass.getuser()
  367. self.requestService(SSHUserAuthClient(user, SSHConnection()))
  368. class SSHUserAuthClient(userauth.SSHUserAuthClient):
  369. usedFiles = []
  370. def getPassword(self, prompt = None):
  371. if not prompt:
  372. prompt = "%s@%s's password: " % (self.user, options['host'])
  373. return deferredAskFrame(prompt,0)
  374. def getPublicKey(self):
  375. files = [x for x in options.identitys if x not in self.usedFiles]
  376. if not files:
  377. return None
  378. file = files[0]
  379. log.msg(file)
  380. self.usedFiles.append(file)
  381. file = os.path.expanduser(file)
  382. file += '.pub'
  383. if not os.path.exists(file):
  384. return
  385. try:
  386. return keys.Key.fromFile(file).blob()
  387. except:
  388. return self.getPublicKey() # try again
  389. def getPrivateKey(self):
  390. file = os.path.expanduser(self.usedFiles[-1])
  391. if not os.path.exists(file):
  392. return None
  393. try:
  394. return defer.succeed(keys.Key.fromFile(file).keyObject)
  395. except keys.BadKeyError as e:
  396. if e.args[0] == 'encrypted key with no password':
  397. prompt = "Enter passphrase for key '%s': " % \
  398. self.usedFiles[-1]
  399. return deferredAskFrame(prompt, 0).addCallback(self._cbGetPrivateKey, 0)
  400. def _cbGetPrivateKey(self, ans, count):
  401. file = os.path.expanduser(self.usedFiles[-1])
  402. try:
  403. return keys.Key.fromFile(file, password = ans).keyObject
  404. except keys.BadKeyError:
  405. if count == 2:
  406. raise
  407. prompt = "Enter passphrase for key '%s': " % \
  408. self.usedFiles[-1]
  409. return deferredAskFrame(prompt, 0).addCallback(self._cbGetPrivateKey, count+1)
  410. class SSHConnection(connection.SSHConnection):
  411. def serviceStarted(self):
  412. if not options['noshell']:
  413. self.openChannel(SSHSession())
  414. if options.localForwards:
  415. for localPort, hostport in options.localForwards:
  416. reactor.listenTCP(localPort,
  417. forwarding.SSHListenForwardingFactory(self,
  418. hostport,
  419. forwarding.SSHListenClientForwardingChannel))
  420. if options.remoteForwards:
  421. for remotePort, hostport in options.remoteForwards:
  422. log.msg('asking for remote forwarding for %s:%s' %
  423. (remotePort, hostport))
  424. data = forwarding.packGlobal_tcpip_forward(
  425. ('0.0.0.0', remotePort))
  426. self.sendGlobalRequest('tcpip-forward', data)
  427. self.remoteForwards[remotePort] = hostport
  428. class SSHSession(channel.SSHChannel):
  429. name = b'session'
  430. def channelOpen(self, foo):
  431. #global globalSession
  432. #globalSession = self
  433. # turn off local echo
  434. self.escapeMode = 1
  435. c = session.SSHSessionClient()
  436. if options['escape']:
  437. c.dataReceived = self.handleInput
  438. else:
  439. c.dataReceived = self.write
  440. c.connectionLost = self.sendEOF
  441. frame.callback = c.dataReceived
  442. frame.canvas.focus_force()
  443. if options['subsystem']:
  444. self.conn.sendRequest(self, b'subsystem', \
  445. common.NS(options['command']))
  446. elif options['command']:
  447. if options['tty']:
  448. term = os.environ.get('TERM', 'xterm')
  449. #winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
  450. winSize = (25,80,0,0) #struct.unpack('4H', winsz)
  451. ptyReqData = session.packRequest_pty_req(term, winSize, '')
  452. self.conn.sendRequest(self, b'pty-req', ptyReqData)
  453. self.conn.sendRequest(self, 'exec', \
  454. common.NS(options['command']))
  455. else:
  456. if not options['notty']:
  457. term = os.environ.get('TERM', 'xterm')
  458. #winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
  459. winSize = (25,80,0,0) #struct.unpack('4H', winsz)
  460. ptyReqData = session.packRequest_pty_req(term, winSize, '')
  461. self.conn.sendRequest(self, b'pty-req', ptyReqData)
  462. self.conn.sendRequest(self, b'shell', b'')
  463. self.conn.transport.transport.setTcpNoDelay(1)
  464. def handleInput(self, char):
  465. #log.msg('handling %s' % repr(char))
  466. if char in ('\n', '\r'):
  467. self.escapeMode = 1
  468. self.write(char)
  469. elif self.escapeMode == 1 and char == options['escape']:
  470. self.escapeMode = 2
  471. elif self.escapeMode == 2:
  472. self.escapeMode = 1 # so we can chain escapes together
  473. if char == '.': # disconnect
  474. log.msg('disconnecting from escape')
  475. reactor.stop()
  476. return
  477. elif char == '\x1a': # ^Z, suspend
  478. # following line courtesy of Erwin@freenode
  479. os.kill(os.getpid(), signal.SIGSTOP)
  480. return
  481. elif char == 'R': # rekey connection
  482. log.msg('rekeying connection')
  483. self.conn.transport.sendKexInit()
  484. return
  485. self.write('~' + char)
  486. else:
  487. self.escapeMode = 0
  488. self.write(char)
  489. def dataReceived(self, data):
  490. if _PY3 and isinstance(data, bytes):
  491. data = data.decode("utf-8")
  492. if options['ansilog']:
  493. print(repr(data))
  494. frame.write(data)
  495. def extReceived(self, t, data):
  496. if t==connection.EXTENDED_DATA_STDERR:
  497. log.msg('got %s stderr data' % len(data))
  498. sys.stderr.write(data)
  499. sys.stderr.flush()
  500. def eofReceived(self):
  501. log.msg('got eof')
  502. sys.stdin.close()
  503. def closed(self):
  504. log.msg('closed %s' % self)
  505. if len(self.conn.channels) == 1: # just us left
  506. reactor.stop()
  507. def request_exit_status(self, data):
  508. global exitStatus
  509. exitStatus = int(struct.unpack('>L', data)[0])
  510. log.msg('exit status: %s' % exitStatus)
  511. def sendEOF(self):
  512. self.conn.sendEOF(self)
  513. if __name__=="__main__":
  514. run()