Salome HOME
Merge branch 'nct/may21'
[tools/sat.git] / test / test_501_paramiko.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3
4 #  Copyright (C) 2010-2018  CEA/DEN
5 #
6 #  This library is free software; you can redistribute it and/or
7 #  modify it under the terms of the GNU Lesser General Public
8 #  License as published by the Free Software Foundation; either
9 #  version 2.1 of the License.
10 #
11 #  This library is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 #  Lesser General Public License for more details.
15 #
16 #  You should have received a copy of the GNU Lesser General Public
17 #  License along with this library; if not, write to the Free Software
18 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19
20
21 """
22 to set id_rsa from/to reflexive on local machine:
23
24     @is231761/home/wambeke/.ssh>ssh wambeke@is231761
25     Password: 
26     Last login: Thu Jun  7 13:34:07 2018 from is231761.intra.cea.fr
27     @is231761/home/wambeke>exit
28     déconnexion
29
30     @is231761/home/wambeke/.ssh> ssh-keygen
31     Generating public/private rsa key pair.
32     Enter file in which to save the key (/home/wambeke/.ssh/id_rsa): 
33     Enter passphrase (empty for no passphrase): 
34     Enter same passphrase again: 
35     Your identification has been saved in /home/wambeke/.ssh/id_rsa.
36     Your public key has been saved in /home/wambeke/.ssh/id_rsa.pub.
37     The key fingerprint is:
38     SHA256:V0IU/wkuCRw42rA5bHFgdJlzDx9EIJyWIBrkzkL3GNA wambeke@is231761
39     The key's randomart image is:
40     +---[RSA 2048]----+
41     |ooo.=+o*o=*.     |
42
43     |                 |
44     +----[SHA256]-----+
45
46     @is231761/home/wambeke/.ssh> ls
47     id_rsa  id_rsa.pub  known_hosts
48     @is231761/home/wambeke/.ssh> rm known_hosts
49     @is231761/home/wambeke/.ssh> ls
50     id_rsa  id_rsa.pub
51
52     @is231761/home/wambeke/.ssh> ssh wambeke@is231761
53     The authenticity of host 'is231761 (127.0.0.1)' can't be established.
54     ECDSA key fingerprint is SHA256:QvrU7Abrbily0bzMjYbRPeKCxDkXT9rQ6pSpcm+yFN4.
55     ECDSA key fingerprint is MD5:6c:95:b7:c7:cd:de:c5:07:8b:3a:9b:14:d1:69:6b:c6.
56     Are you sure you want to continue connecting (yes/no)? yes
57     Warning: Permanently added 'is231761' (ECDSA) to the list of known hosts.
58     Password: 
59     Last login: Thu Jun  7 13:35:07 2018 from is231761.intra.cea.fr
60     @is231761/home/wambeke>exit
61     déconnexion
62     Connection to is231761 closed.
63
64
65     @is231761/home/wambeke/.ssh> lst
66     total 124K
67     -rw-r--r--   1 wambeke lgls  170  7 juin  13:36 known_hosts
68     drwx------   2 wambeke lgls 4,0K  7 juin  13:36 .
69     -rw-r--r--   1 wambeke lgls  398  7 juin  13:35 id_rsa.pub
70     -rw-------   1 wambeke lgls 1,7K  7 juin  13:35 id_rsa
71     drwxr-xr-x 182 wambeke lmpe 104K  6 juin  13:39 ..
72
73
74
75     @is231761/home/wambeke/.ssh> ssh-copy-id -i ~/.ssh/id_rsa.pub is231761
76     /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/wambeke/.ssh/id_rsa.pub"
77     /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
78     /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
79     Password: 
80
81     Number of key(s) added: 1
82
83     Now try logging into the machine, with:   "ssh 'is231761'"
84     and check to make sure that only the key(s) you wanted were added.
85
86     @is231761/home/wambeke/.ssh> ssh wambeke@is231761
87     Last login: Thu Jun  7 13:36:42 2018 from is231761.intra.cea.fr
88     @is231761/home/wambeke>exit
89     déconnexion
90     Connection to is231761 closed.
91
92 """
93
94 import os
95 import sys
96 import unittest
97 import getpass
98
99 verbose = False
100
101 class TestCase(unittest.TestCase):
102   "Test a paramiko connection"""
103
104   def setLoggerParamiko(self):
105     """to get logs of paramiko, useful if problems"""
106     import logging as LOGI
107     loggerPrmk = LOGI.getLogger("paramiko")
108     if len(loggerPrmk.handlers) != 0:
109        print("logging.__file__ %s" % LOGI.__file__)
110        print("logger paramiko have handler set yet, is a surprise")
111        return
112     if not verbose:
113        # stay as it, null
114        return
115
116     #set a paramiko logger verbose
117     handler = LOGI.StreamHandler()
118     msg = "create paramiko logger, with handler on stdout"
119     
120     # handler = LOGI.MemoryHandler()
121     # etc... https://docs.python.org/2/library/logging.handlers.html
122     # msg = "create paramiko logger, with handler in memory"
123
124     # original frm from paramiko
125     # frm = '%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(thread)-3d %(name)s: %(message)s' # noqa
126     frm = '%(levelname)-5s :: %(asctime)s :: %(name)s :: %(message)s'
127     handler.setFormatter(LOGI.Formatter(frm, '%y%m%d_%H%M%S'))
128     loggerPrmk.addHandler(handler)
129       
130     # logger is not notset but low, handlers needs setlevel greater
131     loggerPrmk.setLevel(LOGI.DEBUG)
132     handler.setLevel(LOGI.INFO) # LOGI.DEBUG) # may be other one
133
134     loggerPrmk.info(msg)
135
136
137   '''example from internet
138   def fetch_netmask(self, hostname, port=22):
139     private_key = os.path.expanduser('~/.ssh/id_rsa')
140     connection = open_ssh_connection('wambeke', hostname, port=port, key=private_key)
141
142     get_netmask = ("ip -oneline -family inet address show | grep {}").format(hostname)
143     stdin, stdout, stderr = connection.exec_command(get_netmask)
144     address = parse_address(hostname, stdout)
145     connection.close()
146     return address
147
148   def open_ssh_connection(self, username, hostname, port=22, key=None):
149     client = PK.SSHClient()
150     client.set_missing_host_key_policy(PK.AutoAddPolicy())
151     client.connect(hostname, port=port, timeout=5, username=username, key_filename=key)
152     return client
153   '''
154
155   def test_000(self):
156     self.setLoggerParamiko()
157     
158
159   def test_010(self):
160     # http://docs.paramiko.org/en/2.4/api/agent.html
161
162     try:
163       import paramiko as PK
164     except:
165       print("\nproblem 'import paramiko', no tests")
166       return
167
168     # port=22 # useless
169     username = getpass.getuser()
170     hostname = os.uname()[1]
171     aFile = "/tmp/%s_test_paramiko.tmp" % username
172     cmd = ("pwd; ls -alt {0}; cat {0}").format(aFile)
173     
174     # connect
175     client = PK.SSHClient()
176     client.set_missing_host_key_policy(PK.AutoAddPolicy())  
177     # client.connect(hostname, username=username, password="xxxxx")
178     # client.connect(hostname, username=username, passphrase="yyyy", key_filename="/home/wambeke/.ssh/id_rsa_satjobs_passphrase")
179     # client.connect(hostname, username=username)
180
181     # timeout in seconds
182     client.connect(hostname, username=username, timeout=1.)
183     
184     # obtain session
185     session = client.get_transport().open_session()
186     # Forward local agent
187     PK.agent.AgentRequestHandler(session)
188     # commands executed after this point will see the forwarded agent on the remote end.
189     
190     # one api
191     session.exec_command("date > %s" % aFile)
192     cmd = ("pwd; ls -alt {0}; cat {0} && echo OK").format(aFile)
193     # another api
194     stdin, stdout, stderr = client.exec_command(cmd)
195     output = stdout.read()
196     if verbose:
197       print('stdout:\n%s' % output)
198     self.assertTrue(aFile in output)
199     self.assertTrue("OK" in output)
200     client.close()
201                 
202 if __name__ == '__main__':
203     # verbose = True # human eyes
204     unittest.main(exit=False)
205     pass