09.11.2016 Views

Foundations of Python Network Programming 978-1-4302-3004-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 16 ■ TELNET AND SSH<br />

def process_option(tsocket, command, option):<br />

» if command == DO and option == TTYPE:<br />

» » tsocket.sendall(IAC + WILL + TTYPE)<br />

» » print 'Sending terminal type "mypython"'<br />

» » tsocket.sendall(IAC + SB + TTYPE + '\0' + 'mypython' + IAC + SE)<br />

» elif command in (DO, DONT):<br />

» » print 'Will not', ord(option)<br />

» » tsocket.sendall(IAC + WONT + option)<br />

» elif command in (WILL, WONT):<br />

» » print 'Do not', ord(option)<br />

» » tsocket.sendall(IAC + DONT + option)<br />

t = Telnet('localhost')<br />

# t.set_debuglevel(1) # uncomment this for debugging messages<br />

t.set_option_negotiation_callback(process_option)<br />

t.read_until('login:', 5)<br />

t.write('brandon\n')<br />

t.read_until('assword:', 5) # so P can be capitalized or not<br />

t.write('mypass\n')<br />

n, match, previous_text = t.expect([r'Login incorrect', r'\$'], 10)<br />

if n == 0:<br />

» print "Username and password failed - giving up"<br />

else:<br />

» t.write('exec echo $TERM\n')<br />

» print t.read_all()<br />

For more details about how Telnet options work, again, you can consult the relevant RFCs.<br />

SSH: The Secure Shell<br />

The SSH protocol is one <strong>of</strong> the best-known examples <strong>of</strong> a secure, encrypted protocol among modern<br />

system administrators (HTTPS is probably the very best known).<br />

THE SSH PROTOCOL<br />

Purpose: Secure remote shell, file transfer, port forwarding<br />

Standard: RFC 4250–4256 (2006)<br />

Runs atop: TCP/IP<br />

Default port: 22<br />

Library: paramiko<br />

Exceptions: socket.error, socket.gaierror, paramiko.SSHException<br />

SSH is descended from an earlier protocol that supported “remote login,” “remote shell,” and<br />

“remote file copy” commands named rlogin, rsh, and rcp, which in their time tended to become much<br />

more popular than Telnet at sites that supported them. You cannot imagine what a revelation rcp was, in<br />

278

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!