second try
[vsorcdistro/.git] / mininet / examples / test / test_sshd.py
1 #!/usr/bin/env python
2
3 """
4 Test for sshd.py
5 """
6
7 import unittest
8 from mininet.util import pexpect
9 from mininet.clean import sh
10
11 class testSSHD( unittest.TestCase ):
12
13     opts = [ '\(yes/no\)\?', 'refused', 'Welcome|\$|#', pexpect.EOF, pexpect.TIMEOUT ]
14
15     def connected( self, ip ):
16         "Log into ssh server, check banner, then exit"
17         # Note: this test will fail if "Welcome" is not in the sshd banner
18         # and '#'' or '$'' are not in the prompt
19         p = pexpect.spawn( 'ssh -i /tmp/ssh/test_rsa %s' % ip, timeout=10 )
20         while True:
21             index = p.expect( self.opts )
22             if index == 0:
23                 print( p.match.group(0) )
24                 p.sendline( 'yes' )
25             elif index == 1:
26                 return False
27             elif index == 2:
28                 p.sendline( 'exit' )
29                 p.wait()
30                 return True
31             else:
32                 return False
33
34     def setUp( self ):
35         # create public key pair for testing
36         sh( 'rm -rf /tmp/ssh' )
37         sh( 'mkdir /tmp/ssh' )
38         sh( "ssh-keygen -t rsa -P '' -f /tmp/ssh/test_rsa" )
39         sh( 'cat /tmp/ssh/test_rsa.pub >> /tmp/ssh/authorized_keys' )
40         cmd = ( 'python -m mininet.examples.sshd -D '
41                 '-o AuthorizedKeysFile=/tmp/ssh/authorized_keys '
42                 '-o StrictModes=no -o UseDNS=no -u0' )
43         # run example with custom sshd args
44         self.net = pexpect.spawn( cmd )
45         self.net.expect( 'mininet>' )
46
47     def testSSH( self ):
48         "Verify that we can ssh into all hosts (h1 to h4)"
49         for h in range( 1, 5 ):
50             self.assertTrue( self.connected( '10.0.0.%d' % h ) )
51
52     def tearDown( self ):
53         self.net.sendline( 'exit' )
54         self.net.wait()
55         # remove public key pair
56         sh( 'rm -rf /tmp/ssh' )
57
58 if __name__ == '__main__':
59     unittest.main()
60