conch.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. # -*- test-case-name: twisted.conch.test.test_conch -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. #
  6. # $Id: conch.py,v 1.65 2004/03/11 00:29:14 z3p Exp $
  7. #""" Implementation module for the `conch` command.
  8. #"""
  9. from __future__ import print_function
  10. from twisted.conch.client import connect, default, options
  11. from twisted.conch.error import ConchError
  12. from twisted.conch.ssh import connection, common
  13. from twisted.conch.ssh import session, forwarding, channel
  14. from twisted.internet import reactor, stdio, task
  15. from twisted.python import log, usage
  16. import os, sys, getpass, struct, tty, fcntl, signal
  17. class ClientOptions(options.ConchOptions):
  18. synopsis = """Usage: conch [options] host [command]
  19. """
  20. longdesc = ("conch is a SSHv2 client that allows logging into a remote "
  21. "machine and executing commands.")
  22. optParameters = [['escape', 'e', '~'],
  23. ['localforward', 'L', None, 'listen-port:host:port Forward local port to remote address'],
  24. ['remoteforward', 'R', None, 'listen-port:host:port Forward remote port to local address'],
  25. ]
  26. optFlags = [['null', 'n', 'Redirect input from /dev/null.'],
  27. ['fork', 'f', 'Fork to background after authentication.'],
  28. ['tty', 't', 'Tty; allocate a tty even if command is given.'],
  29. ['notty', 'T', 'Do not allocate a tty.'],
  30. ['noshell', 'N', 'Do not execute a shell or command.'],
  31. ['subsystem', 's', 'Invoke command (mandatory) as SSH2 subsystem.'],
  32. ]
  33. compData = usage.Completions(
  34. mutuallyExclusive=[("tty", "notty")],
  35. optActions={
  36. "localforward": usage.Completer(descr="listen-port:host:port"),
  37. "remoteforward": usage.Completer(descr="listen-port:host:port")},
  38. extraActions=[usage.CompleteUserAtHost(),
  39. usage.Completer(descr="command"),
  40. usage.Completer(descr="argument", repeat=True)]
  41. )
  42. localForwards = []
  43. remoteForwards = []
  44. def opt_escape(self, esc):
  45. "Set escape character; ``none'' = disable"
  46. if esc == 'none':
  47. self['escape'] = None
  48. elif esc[0] == '^' and len(esc) == 2:
  49. self['escape'] = chr(ord(esc[1])-64)
  50. elif len(esc) == 1:
  51. self['escape'] = esc
  52. else:
  53. sys.exit("Bad escape character '%s'." % esc)
  54. def opt_localforward(self, f):
  55. "Forward local port to remote address (lport:host:port)"
  56. localPort, remoteHost, remotePort = f.split(':') # doesn't do v6 yet
  57. localPort = int(localPort)
  58. remotePort = int(remotePort)
  59. self.localForwards.append((localPort, (remoteHost, remotePort)))
  60. def opt_remoteforward(self, f):
  61. """Forward remote port to local address (rport:host:port)"""
  62. remotePort, connHost, connPort = f.split(':') # doesn't do v6 yet
  63. remotePort = int(remotePort)
  64. connPort = int(connPort)
  65. self.remoteForwards.append((remotePort, (connHost, connPort)))
  66. def parseArgs(self, host, *command):
  67. self['host'] = host
  68. self['command'] = ' '.join(command)
  69. # Rest of code in "run"
  70. options = None
  71. conn = None
  72. exitStatus = 0
  73. old = None
  74. _inRawMode = 0
  75. _savedRawMode = None
  76. def run():
  77. global options, old
  78. args = sys.argv[1:]
  79. if '-l' in args: # cvs is an idiot
  80. i = args.index('-l')
  81. args = args[i:i+2]+args
  82. del args[i+2:i+4]
  83. for arg in args[:]:
  84. try:
  85. i = args.index(arg)
  86. if arg[:2] == '-o' and args[i+1][0]!='-':
  87. args[i:i+2] = [] # suck on it scp
  88. except ValueError:
  89. pass
  90. options = ClientOptions()
  91. try:
  92. options.parseOptions(args)
  93. except usage.UsageError as u:
  94. print('ERROR: %s' % u)
  95. options.opt_help()
  96. sys.exit(1)
  97. if options['log']:
  98. if options['logfile']:
  99. if options['logfile'] == '-':
  100. f = sys.stdout
  101. else:
  102. f = open(options['logfile'], 'a+')
  103. else:
  104. f = sys.stderr
  105. realout = sys.stdout
  106. log.startLogging(f)
  107. sys.stdout = realout
  108. else:
  109. log.discardLogs()
  110. doConnect()
  111. fd = sys.stdin.fileno()
  112. try:
  113. old = tty.tcgetattr(fd)
  114. except:
  115. old = None
  116. try:
  117. oldUSR1 = signal.signal(signal.SIGUSR1, lambda *a: reactor.callLater(0, reConnect))
  118. except:
  119. oldUSR1 = None
  120. try:
  121. reactor.run()
  122. finally:
  123. if old:
  124. tty.tcsetattr(fd, tty.TCSANOW, old)
  125. if oldUSR1:
  126. signal.signal(signal.SIGUSR1, oldUSR1)
  127. if (options['command'] and options['tty']) or not options['notty']:
  128. signal.signal(signal.SIGWINCH, signal.SIG_DFL)
  129. if sys.stdout.isatty() and not options['command']:
  130. print('Connection to %s closed.' % options['host'])
  131. sys.exit(exitStatus)
  132. def handleError():
  133. from twisted.python import failure
  134. global exitStatus
  135. exitStatus = 2
  136. reactor.callLater(0.01, _stopReactor)
  137. log.err(failure.Failure())
  138. raise
  139. def _stopReactor():
  140. try:
  141. reactor.stop()
  142. except: pass
  143. def doConnect():
  144. # log.deferr = handleError # HACK
  145. if '@' in options['host']:
  146. options['user'], options['host'] = options['host'].split('@',1)
  147. if not options.identitys:
  148. options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa']
  149. host = options['host']
  150. if not options['user']:
  151. options['user'] = getpass.getuser()
  152. if not options['port']:
  153. options['port'] = 22
  154. else:
  155. options['port'] = int(options['port'])
  156. host = options['host']
  157. port = options['port']
  158. vhk = default.verifyHostKey
  159. if not options['host-key-algorithms']:
  160. options['host-key-algorithms'] = default.getHostKeyAlgorithms(
  161. host, options)
  162. uao = default.SSHUserAuthClient(options['user'], options, SSHConnection())
  163. connect.connect(host, port, options, vhk, uao).addErrback(_ebExit)
  164. def _ebExit(f):
  165. global exitStatus
  166. exitStatus = "conch: exiting with error %s" % f
  167. reactor.callLater(0.1, _stopReactor)
  168. def onConnect():
  169. # if keyAgent and options['agent']:
  170. # cc = protocol.ClientCreator(reactor, SSHAgentForwardingLocal, conn)
  171. # cc.connectUNIX(os.environ['SSH_AUTH_SOCK'])
  172. if hasattr(conn.transport, 'sendIgnore'):
  173. _KeepAlive(conn)
  174. if options.localForwards:
  175. for localPort, hostport in options.localForwards:
  176. s = reactor.listenTCP(localPort,
  177. forwarding.SSHListenForwardingFactory(conn,
  178. hostport,
  179. SSHListenClientForwardingChannel))
  180. conn.localForwards.append(s)
  181. if options.remoteForwards:
  182. for remotePort, hostport in options.remoteForwards:
  183. log.msg('asking for remote forwarding for %s:%s' %
  184. (remotePort, hostport))
  185. conn.requestRemoteForwarding(remotePort, hostport)
  186. reactor.addSystemEventTrigger('before', 'shutdown', beforeShutdown)
  187. if not options['noshell'] or options['agent']:
  188. conn.openChannel(SSHSession())
  189. if options['fork']:
  190. if os.fork():
  191. os._exit(0)
  192. os.setsid()
  193. for i in range(3):
  194. try:
  195. os.close(i)
  196. except OSError as e:
  197. import errno
  198. if e.errno != errno.EBADF:
  199. raise
  200. def reConnect():
  201. beforeShutdown()
  202. conn.transport.transport.loseConnection()
  203. def beforeShutdown():
  204. remoteForwards = options.remoteForwards
  205. for remotePort, hostport in remoteForwards:
  206. log.msg('cancelling %s:%s' % (remotePort, hostport))
  207. conn.cancelRemoteForwarding(remotePort)
  208. def stopConnection():
  209. if not options['reconnect']:
  210. reactor.callLater(0.1, _stopReactor)
  211. class _KeepAlive:
  212. def __init__(self, conn):
  213. self.conn = conn
  214. self.globalTimeout = None
  215. self.lc = task.LoopingCall(self.sendGlobal)
  216. self.lc.start(300)
  217. def sendGlobal(self):
  218. d = self.conn.sendGlobalRequest(b"conch-keep-alive@twistedmatrix.com",
  219. b"", wantReply = 1)
  220. d.addBoth(self._cbGlobal)
  221. self.globalTimeout = reactor.callLater(30, self._ebGlobal)
  222. def _cbGlobal(self, res):
  223. if self.globalTimeout:
  224. self.globalTimeout.cancel()
  225. self.globalTimeout = None
  226. def _ebGlobal(self):
  227. if self.globalTimeout:
  228. self.globalTimeout = None
  229. self.conn.transport.loseConnection()
  230. class SSHConnection(connection.SSHConnection):
  231. def serviceStarted(self):
  232. global conn
  233. conn = self
  234. self.localForwards = []
  235. self.remoteForwards = {}
  236. if not isinstance(self, connection.SSHConnection):
  237. # make these fall through
  238. del self.__class__.requestRemoteForwarding
  239. del self.__class__.cancelRemoteForwarding
  240. onConnect()
  241. def serviceStopped(self):
  242. lf = self.localForwards
  243. self.localForwards = []
  244. for s in lf:
  245. s.loseConnection()
  246. stopConnection()
  247. def requestRemoteForwarding(self, remotePort, hostport):
  248. data = forwarding.packGlobal_tcpip_forward(('0.0.0.0', remotePort))
  249. d = self.sendGlobalRequest(b'tcpip-forward', data,
  250. wantReply=1)
  251. log.msg('requesting remote forwarding %s:%s' %(remotePort, hostport))
  252. d.addCallback(self._cbRemoteForwarding, remotePort, hostport)
  253. d.addErrback(self._ebRemoteForwarding, remotePort, hostport)
  254. def _cbRemoteForwarding(self, result, remotePort, hostport):
  255. log.msg('accepted remote forwarding %s:%s' % (remotePort, hostport))
  256. self.remoteForwards[remotePort] = hostport
  257. log.msg(repr(self.remoteForwards))
  258. def _ebRemoteForwarding(self, f, remotePort, hostport):
  259. log.msg('remote forwarding %s:%s failed' % (remotePort, hostport))
  260. log.msg(f)
  261. def cancelRemoteForwarding(self, remotePort):
  262. data = forwarding.packGlobal_tcpip_forward(('0.0.0.0', remotePort))
  263. self.sendGlobalRequest(b'cancel-tcpip-forward', data)
  264. log.msg('cancelling remote forwarding %s' % remotePort)
  265. try:
  266. del self.remoteForwards[remotePort]
  267. except:
  268. pass
  269. log.msg(repr(self.remoteForwards))
  270. def channel_forwarded_tcpip(self, windowSize, maxPacket, data):
  271. log.msg('%s %s' % ('FTCP', repr(data)))
  272. remoteHP, origHP = forwarding.unpackOpen_forwarded_tcpip(data)
  273. log.msg(self.remoteForwards)
  274. log.msg(remoteHP)
  275. if remoteHP[1] in self.remoteForwards:
  276. connectHP = self.remoteForwards[remoteHP[1]]
  277. log.msg('connect forwarding %s' % (connectHP,))
  278. return SSHConnectForwardingChannel(connectHP,
  279. remoteWindow = windowSize,
  280. remoteMaxPacket = maxPacket,
  281. conn = self)
  282. else:
  283. raise ConchError(connection.OPEN_CONNECT_FAILED, "don't know about that port")
  284. # def channel_auth_agent_openssh_com(self, windowSize, maxPacket, data):
  285. # if options['agent'] and keyAgent:
  286. # return agent.SSHAgentForwardingChannel(remoteWindow = windowSize,
  287. # remoteMaxPacket = maxPacket,
  288. # conn = self)
  289. # else:
  290. # return connection.OPEN_CONNECT_FAILED, "don't have an agent"
  291. def channelClosed(self, channel):
  292. log.msg('connection closing %s' % channel)
  293. log.msg(self.channels)
  294. if len(self.channels) == 1: # just us left
  295. log.msg('stopping connection')
  296. stopConnection()
  297. else:
  298. # because of the unix thing
  299. self.__class__.__bases__[0].channelClosed(self, channel)
  300. class SSHSession(channel.SSHChannel):
  301. name = b'session'
  302. def channelOpen(self, foo):
  303. log.msg('session %s open' % self.id)
  304. if options['agent']:
  305. d = self.conn.sendRequest(self, b'auth-agent-req@openssh.com', b'', wantReply=1)
  306. d.addBoth(lambda x:log.msg(x))
  307. if options['noshell']: return
  308. if (options['command'] and options['tty']) or not options['notty']:
  309. _enterRawMode()
  310. c = session.SSHSessionClient()
  311. if options['escape'] and not options['notty']:
  312. self.escapeMode = 1
  313. c.dataReceived = self.handleInput
  314. else:
  315. c.dataReceived = self.write
  316. c.connectionLost = lambda x=None,s=self:s.sendEOF()
  317. self.stdio = stdio.StandardIO(c)
  318. fd = 0
  319. if options['subsystem']:
  320. self.conn.sendRequest(self, b'subsystem', \
  321. common.NS(options['command']))
  322. elif options['command']:
  323. if options['tty']:
  324. term = os.environ['TERM']
  325. winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
  326. winSize = struct.unpack('4H', winsz)
  327. ptyReqData = session.packRequest_pty_req(term, winSize, '')
  328. self.conn.sendRequest(self, b'pty-req', ptyReqData)
  329. signal.signal(signal.SIGWINCH, self._windowResized)
  330. self.conn.sendRequest(self, b'exec', \
  331. common.NS(options['command']))
  332. else:
  333. if not options['notty']:
  334. term = os.environ['TERM']
  335. winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
  336. winSize = struct.unpack('4H', winsz)
  337. ptyReqData = session.packRequest_pty_req(term, winSize, '')
  338. self.conn.sendRequest(self, b'pty-req', ptyReqData)
  339. signal.signal(signal.SIGWINCH, self._windowResized)
  340. self.conn.sendRequest(self, b'shell', b'')
  341. #if hasattr(conn.transport, 'transport'):
  342. # conn.transport.transport.setTcpNoDelay(1)
  343. def handleInput(self, char):
  344. #log.msg('handling %s' % repr(char))
  345. if char in ('\n', '\r'):
  346. self.escapeMode = 1
  347. self.write(char)
  348. elif self.escapeMode == 1 and char == options['escape']:
  349. self.escapeMode = 2
  350. elif self.escapeMode == 2:
  351. self.escapeMode = 1 # so we can chain escapes together
  352. if char == '.': # disconnect
  353. log.msg('disconnecting from escape')
  354. stopConnection()
  355. return
  356. elif char == '\x1a': # ^Z, suspend
  357. def _():
  358. _leaveRawMode()
  359. sys.stdout.flush()
  360. sys.stdin.flush()
  361. os.kill(os.getpid(), signal.SIGTSTP)
  362. _enterRawMode()
  363. reactor.callLater(0, _)
  364. return
  365. elif char == 'R': # rekey connection
  366. log.msg('rekeying connection')
  367. self.conn.transport.sendKexInit()
  368. return
  369. elif char == '#': # display connections
  370. self.stdio.write('\r\nThe following connections are open:\r\n')
  371. channels = self.conn.channels.keys()
  372. channels.sort()
  373. for channelId in channels:
  374. self.stdio.write(' #%i %s\r\n' % (channelId, str(self.conn.channels[channelId])))
  375. return
  376. self.write('~' + char)
  377. else:
  378. self.escapeMode = 0
  379. self.write(char)
  380. def dataReceived(self, data):
  381. self.stdio.write(data)
  382. def extReceived(self, t, data):
  383. if t==connection.EXTENDED_DATA_STDERR:
  384. log.msg('got %s stderr data' % len(data))
  385. sys.stderr.write(data)
  386. def eofReceived(self):
  387. log.msg('got eof')
  388. self.stdio.loseWriteConnection()
  389. def closeReceived(self):
  390. log.msg('remote side closed %s' % self)
  391. self.conn.sendClose(self)
  392. def closed(self):
  393. global old
  394. log.msg('closed %s' % self)
  395. log.msg(repr(self.conn.channels))
  396. def request_exit_status(self, data):
  397. global exitStatus
  398. exitStatus = int(struct.unpack('>L', data)[0])
  399. log.msg('exit status: %s' % exitStatus)
  400. def sendEOF(self):
  401. self.conn.sendEOF(self)
  402. def stopWriting(self):
  403. self.stdio.pauseProducing()
  404. def startWriting(self):
  405. self.stdio.resumeProducing()
  406. def _windowResized(self, *args):
  407. winsz = fcntl.ioctl(0, tty.TIOCGWINSZ, '12345678')
  408. winSize = struct.unpack('4H', winsz)
  409. newSize = winSize[1], winSize[0], winSize[2], winSize[3]
  410. self.conn.sendRequest(self, b'window-change', struct.pack('!4L', *newSize))
  411. class SSHListenClientForwardingChannel(forwarding.SSHListenClientForwardingChannel): pass
  412. class SSHConnectForwardingChannel(forwarding.SSHConnectForwardingChannel): pass
  413. def _leaveRawMode():
  414. global _inRawMode
  415. if not _inRawMode:
  416. return
  417. fd = sys.stdin.fileno()
  418. tty.tcsetattr(fd, tty.TCSANOW, _savedRawMode)
  419. _inRawMode = 0
  420. def _enterRawMode():
  421. global _inRawMode, _savedRawMode
  422. if _inRawMode:
  423. return
  424. fd = sys.stdin.fileno()
  425. try:
  426. old = tty.tcgetattr(fd)
  427. new = old[:]
  428. except:
  429. log.msg('not a typewriter!')
  430. else:
  431. # iflage
  432. new[0] = new[0] | tty.IGNPAR
  433. new[0] = new[0] & ~(tty.ISTRIP | tty.INLCR | tty.IGNCR | tty.ICRNL |
  434. tty.IXON | tty.IXANY | tty.IXOFF)
  435. if hasattr(tty, 'IUCLC'):
  436. new[0] = new[0] & ~tty.IUCLC
  437. # lflag
  438. new[3] = new[3] & ~(tty.ISIG | tty.ICANON | tty.ECHO | tty.ECHO |
  439. tty.ECHOE | tty.ECHOK | tty.ECHONL)
  440. if hasattr(tty, 'IEXTEN'):
  441. new[3] = new[3] & ~tty.IEXTEN
  442. #oflag
  443. new[1] = new[1] & ~tty.OPOST
  444. new[6][tty.VMIN] = 1
  445. new[6][tty.VTIME] = 0
  446. _savedRawMode = old
  447. tty.tcsetattr(fd, tty.TCSANOW, new)
  448. #tty.setraw(fd)
  449. _inRawMode = 1
  450. if __name__ == '__main__':
  451. run()