utils.py 21.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#
# Copyright (C) 2009 INRA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

__author__ = 'Plateforme bioinformatique Midi Pyrenees'
__copyright__ = 'Copyright (C) 2009 INRA'
__license__ = 'GNU General Public License'
__version__ = '1.0'
22
__email__ = 'support.bioinfo.genotoul@inra.fr'
23
24
25
26
27
28
__status__ = 'beta'

import glob
import os
import string, gzip, bz2
import tarfile, tempfile
Gerald Salin's avatar
Gerald Salin committed
29
import logging
30
31
from shutil import copyfile, rmtree
import re
32
import base64
Penom Nom's avatar
Penom Nom committed
33
34
import pty
import sys
35
from subprocess import call
Penom Nom's avatar
Penom Nom committed
36

37
38
39
40
41
42
43
class Utils(object):
    """
    Class Utils: in charge to all the programme utilities
    """

    # Files with this extensions won't be compressed if asked
    UNCOMPRESS_EXTENSION = [".gz", ".zip", ".bam", ".bz", ".bz2"]
Penom Nom's avatar
Penom Nom committed
44
45
46
47
    
    # CASAVA filename format
    CASAVA_FILENAME = { 'sample' : 1, 'barcode' : 2, 'lane' : 3, 'read' : 4, 'package' : 5 }
    CASAVA_FILENAME_SEPARATOR = '_'
48

49
50
    PASS_KEY = '1234123412341234123412341234'
    
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
    @staticmethod
    def gzip(file, out_dir, delete=False):
        """
          Gzip compress the given file.
          @param file    : the file to gzip 
          @param out_dir : the out directory where to store the gziped file
          @param delete  : delete files     
          @return        : the compressed file path
        """
        # If the file is not already a compressed file
        if os.path.splitext(file)[1] not in Utils.UNCOMPRESS_EXTENSION:
            f_in = open(file, 'rb')
            f_out_name = os.path.join(out_dir, os.path.basename(file)) + ".gz"
            f_out = gzip.open(f_out_name, 'wb')
            f_out.writelines(f_in)
            f_out.close()
            f_in.close()
        # Otherwise, just copy it
        else:
            f_out_name = os.path.join(out_dir, os.path.basename(file))
            copyfile(file, f_out_name)
        
        # Finaly try to delete the original file if asked to do so
        try:
            if delete:
                os.remove(file)
        except:
            pass
        return f_out_name


    @staticmethod
    def gunzip(file, out_dir):
        """
          Gunzip given file.
          @param file    : the file to gunzip 
          @param out_dir : the out directory where to store the decompressed file 
          @return        : the uncompressed file path
        """
        f_in = gzip.open(file)
        f_out_name = os.path.join(out_dir, os.path.splitext(os.path.basename(file))[0])
        f_out = open(f_out_name, 'w')
        f_out.writelines(f_in)
        f_out.close()
        f_in.close()
        return f_out_name

98
99
100
    @staticmethod
    def get_storage_size(start_path):
        total_size = 0
Penom Nom's avatar
Penom Nom committed
101
102
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
103
104
105
                fp = os.path.join(dirpath, f)
                total_size += os.path.getsize(fp)
        return total_size
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242

    @staticmethod
    def bz2(file, out_dir, delete=False):
        """
          Bzip compress the given file.
          @param file    : the file to compress 
          @param out_dir : the out directory where to store the compressed file
          @param delete  : delete files     
          @return        : the compressed file path
        """
        # If the file is not already a compressed file
        if os.path.splitext(file)[1] not in Utils.UNCOMPRESS_EXTENSION:
            f_in = open(file, 'rb')
            f_out_name = os.path.join(out_dir, os.path.basename(file)) + ".bz2"
            f_out = bz2.BZ2File(f_out_name, 'wb')
            f_out.writelines(f_in)
            f_out.close()
            f_in.close()
        # Otherwise, just copy it
        else:
            f_out_name = os.path.join(out_dir, os.path.basename(file))
            copyfile(file, f_out_name)
        
        # Finaly try to delete the original file if asked to do so
        try:
            if delete:
                os.remove(file)
        except:
            pass

        return f_out_name


    @staticmethod
    def uncompress_bz2(file, out_dir):
        """
          Bzip compress the given file.
          @param file    : the file to compress 
          @param out_dir : the out directory where to store the compressed file     
          @return        : the compressed file path
        """
        f_in = bz2.BZ2File(file)
        f_out_name = os.path.join(out_dir, os.path.splitext(os.path.basename(file))[0])
        f_out = open(f_out_name, 'w')
        f_out.writelines(f_in)
        f_out.close()
        f_in.close()
        return f_out_name


    @staticmethod
    def tar_files(files, out_tar_name, delete=False):
        """
        Tar all files given.
          @param files        : table of files
          @param out_tar_name : the full output tar path (archive name included)
          @param delete       : delete files     
          @return             : the path to the tar file
        """
        tarf = tarfile.open(out_tar_name, "w")
        for file in files:
            if os.path.isfile(file) :
                (head, tail)= os.path.split(file)
                os.chdir(head)
                tarf.add(tail)
        tarf.close()
        
        for file in files:
            try:
                if delete:
                    os.remove(file)
            except:
                pass
        return out_tar_name


    @staticmethod
    def yield_files(files_tab):
        """
        yield objects to untar
        """
        for file in files_tab:
            yield file


    @staticmethod
    def untar_files(archive, pattern, out_dir):
        """
        Tar all files given.
          @param archive : the tar file
          @param pattern : the extension to search for
          @param out_dir : where should be untar the files
          @return        : a list of untared files
        """
        tarf = tarfile.open(archive)
        files = []
        files_to_return = []
        for tarinfo in tarf:
            if os.path.splitext(tarinfo.name)[1] == "."+pattern:
                files.append(tarinfo)
                files_to_return.append(os.path.join(out_dir, tarinfo.name))
        tarf.extractall(path=out_dir, members=Utils.yield_files(files))
        tarf.close()
        return files_to_return
        
        
    @staticmethod
    def tar_dir(directory, out_tar_name, delete=False):
        """
        Tar the given directory.
          @param directory    : the directory to tar
          @param out_tar_name : the full output tar path (archive name included)
          @param delete       : delete dir
          @return             : the path to the tar file
        """
        tarf = tarfile.open(out_tar_name, "w")
        os.chdir(directory)
        tarf.add(".")
        tarf.close()
        try:
            if delete:
                shutil.remove(directory)
        except:
            pass
        return out_tar_name
    
    
    @staticmethod
    def getUniqueCombinaison(items, n):
        """
        Return all combinaison for the list
          @param items : the list
          @param n : the max depth
        """
        if n==0: 
            yield []
        else:
Penom Nom's avatar
Penom Nom committed
243
            for i in range( len(items) - n+1 ):
244
245
246
247
248
249
250
251
252
253
254
                for j in Utils.getUniqueCombinaison( items[i+1:], n-1 ):
                    yield [items[i]] + j

    
    @staticmethod             
    def getSizesUniqueCombinaison(items):
        """
        Return all combinaison for the list
          @param items : the list
        """
        res = []
Penom Nom's avatar
Penom Nom committed
255
        for n in range(1,len(items)+1):
256
257
            res += Utils.getUniqueCombinaison(items,n)
        return res
Penom Nom's avatar
Penom Nom committed
258
259
260
261
262
263
264
265
266
267
268
 
    
    @staticmethod
    def split_pair( file_list, is_casava=False ):
        """
        Return the list of read 1 and the list of read 1 from a list
          @param file_list : the list
          @param is_casava : files names in file_list are in CASVAVA format 
        """
        read_1_list = []
        read_2_list = []
269
        logging.getLogger("Utils").debug("split_pair. Entering")
Penom Nom's avatar
Penom Nom committed
270
        if is_casava:
271
            logging.getLogger("Utils").debug("split_pair. is_casava")
Penom Nom's avatar
Penom Nom committed
272
            for file in file_list:
273
                logging.getLogger("Utils").debug("split_pair. file = " + file)
Penom Nom's avatar
Penom Nom committed
274
275
                basename_without_ext = os.path.basename(file).split(".")[0]
                file_name_fields = basename_without_ext.split(Utils.CASAVA_FILENAME_SEPARATOR)
Penom Nom's avatar
Penom Nom committed
276
277
278
279
280
281
                read_tag = file_name_fields[Utils.CASAVA_FILENAME['read']-1]
                if read_tag == "R1":
                    read_1_list.append(file)
                else:
                    read_2_list.append(file)
        else:
282
            sorted_list = sorted( file_list )
283
284
            logging.getLogger("Utils").debug("split_pair. file_list = " + ", ".join(file_list))
            logging.getLogger("Utils").debug("split_pair. sorted_list = " + ", ".join(sorted_list))
285
            for i in range(0,len(sorted_list),2):
286
287
                logging.getLogger("Utils").debug("split_pair. sorted_list[i] = " + sorted_list[i])
                logging.getLogger("Utils").debug("split_pair. sorted_list[i+1] = " + sorted_list[i+1])
288
289
290
                read_1_list.append(sorted_list[i])
                read_2_list.append(sorted_list[i+1])
            
Penom Nom's avatar
Penom Nom committed
291
292
        return [read_1_list, read_2_list]

293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
    @staticmethod
    def split_pair_and_index ( file_list, is_casava=False ):
        """
        Return the list of read 1, the list of read 2 and the list of index read from a list
          @param file_list : the list
          @param is_casava : files names in file_list are in CASVAVA format 
        """
        read_1_list = []
        read_2_list = []
        read_index_list = []
        logging.getLogger("Utils").debug("split_pair_and_index. Entering")
        if is_casava:
            logging.getLogger("Utils").debug("split_pair_and_index. is_casava")
            for file in file_list:
                logging.getLogger("Utils").debug("split_pair_and_index. file = " + file)
                basename_without_ext = os.path.basename(file).split(".")[0]
                file_name_fields = basename_without_ext.split(Utils.CASAVA_FILENAME_SEPARATOR)
                read_tag = file_name_fields[Utils.CASAVA_FILENAME['read']-1]
                if read_tag == "R1":
                    read_1_list.append(file)
                elif read_tag == "R2":
                    read_2_list.append(file)
                else:
                    read_index_list.append(file)
        else:
            sorted_list = sorted( file_list )
            logging.getLogger("Utils").debug("split_pair_and_index. file_list = " + ", ".join(file_list))
            logging.getLogger("Utils").debug("split_pair_and_index. sorted_list = " + ", ".join(sorted_list))
            for i in range(0,len(sorted_list),3):
                logging.getLogger("Utils").debug("split_pair_and_index. sorted_list[i] = " + sorted_list[i])
                logging.getLogger("Utils").debug("split_pair_and_index. sorted_list[i+1] = " + sorted_list[i+1])
                logging.getLogger("Utils").debug("split_pair_and_index. sorted_list[i+1] = " + sorted_list[i+2])
                read_1_list.append(sorted_list[i])
                read_2_list.append(sorted_list[i+1])
                read_index_list.append(sorted_list[i+2])
            
        return [read_1_list, read_2_list, read_index_list]
    
Penom Nom's avatar
Penom Nom committed
331
332
333
334
335
336
337
338
    @staticmethod
    def get_group_basenames( file_list, group_by ):
        """
        Return the list of prefix according to keywords. Ex : [/home/sampleA_ATGCTC_L001_R1_001.fastq.gz, /home/sampleA_ATGCTC_L001_R2_001.fastq.gz, /home/sampleB_ATGCCG_L001_R1_001.fastq.gz]  => [sampleA_ATGCTC_L001_R1, sampleA_ATGCTC_L001_R2, sampleB_ATGCCG_L001_R1]
          @param file_list : the list of files (files names are in CASVAVA format)
          @param group_by : CASAVA_FILENAME key (ex : read)
        """
        group_basenames = {}
ckuchly's avatar
ckuchly committed
339
        logging.getLogger("Utils").debug("get_group_basenames. file_list = " + ",".join(file_list))
Penom Nom's avatar
Penom Nom committed
340

mmanno's avatar
mmanno committed
341
        for file in file_list:  
ckuchly's avatar
ckuchly committed
342
            
Penom Nom's avatar
Penom Nom committed
343
344
345
            file_name_fields = os.path.basename(file).split(Utils.CASAVA_FILENAME_SEPARATOR)
        
            group_tag = Utils.CASAVA_FILENAME_SEPARATOR.join( file_name_fields[:Utils.CASAVA_FILENAME[group_by]] )
ckuchly's avatar
ckuchly committed
346
            
Penom Nom's avatar
Penom Nom committed
347
        
Penom Nom's avatar
Penom Nom committed
348
            if group_tag in group_basenames :
Penom Nom's avatar
Penom Nom committed
349
350
351
                group_basenames[group_tag].append(file)
            else:
                group_basenames[group_tag] = [file]
mmanno's avatar
mmanno committed
352
        logging.getLogger("Utils").debug("get_group_basenames. group_basenames = " + ",".join(group_basenames))
Penom Nom's avatar
Penom Nom committed
353
        return group_basenames
Penom Nom's avatar
Penom Nom committed
354
355
356
357
358
359
360
361
362
363
364
365

    @staticmethod
    def get_filepath_by_prefix( path_list, prefixes ):
        """
        Gather files path with same prefix. Ex :
        list [/home/sample1_L002.fastq, /home/sample2_L002.fastq, /home/sample1_L003.fastq] 
        with prefixes [sample1, sample2]
        return {'sample1':[/home/sample1_L002.fastq, /home/sample1_L003.fastq], 'sample2':[/home/sample2_L002.fastq]}
          @param path_list : the list of files
          @param prefixes : prefix to gather
        """
        path_groups = {}
Gerald Salin's avatar
Gerald Salin committed
366
        logging.getLogger("Utils").debug("get_filepath_by_prefix. prefixes = " + ", ".join(prefixes)) 
Penom Nom's avatar
Penom Nom committed
367
368
369
370
371
        for current_prefix in prefixes:
            path_groups[current_prefix] = []           
            for file_path in path_list:
                if os.path.basename(file_path).startswith(current_prefix):
                    path_groups[current_prefix].append(file_path)
Gerald Salin's avatar
Gerald Salin committed
372
            logging.getLogger("Utils").debug("get_filepath_by_prefix. path_groups[current_prefix] = " + ", ".join(path_groups[current_prefix]))
Penom Nom's avatar
Penom Nom committed
373
        
374
375
        return path_groups
    
376
377
    @staticmethod
    def encode_passwd(clear):
Penom Nom's avatar
Penom Nom committed
378
379
        return base64.urlsafe_b64encode(clear.encode()).decode()
        """
380
381
382
383
384
385
        enc = []
        for i in range(len(clear)):
            key_c = Utils.PASS_KEY[i % len(Utils.PASS_KEY)]
            enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
            enc.append(enc_c)
        return base64.urlsafe_b64encode("".join(enc))
Penom Nom's avatar
Penom Nom committed
386
        """
387
388
389
    
    @staticmethod
    def decode_passwd(enc):
Penom Nom's avatar
Penom Nom committed
390
391
        return base64.urlsafe_b64decode(enc.encode()).decode()
        """
392
393
394
395
396
397
398
        dec = []
        enc = base64.urlsafe_b64decode(enc)
        for i in range(len(enc)):
            key_c = Utils.PASS_KEY[i % len(Utils.PASS_KEY)]
            dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
            dec.append(dec_c)
        return "".join(dec)
Penom Nom's avatar
Penom Nom committed
399
        """
Penom Nom's avatar
Penom Nom committed
400
    
401
402
403
404
405
406
407
408
409
410
411
    
    @staticmethod
    def get_project_dirname(project_id, project_name):
        return "Project_%s.%s" % ( re.sub( r"[\s\/]", "_", project_name), project_id )
    @staticmethod
    def get_run_dirname(run_id, run_name):
        return "Run_%s.%s" % ( re.sub( r"[^A-Za-z0-9]", "_", run_name), run_id)
    @staticmethod
    def get_analyse_dirname(analyse_id, analyse_name):
        return "Analyse_%s.%s"%( re.sub( r"[\s\/]", "_", analyse_name), analyse_id )
    
Penom Nom's avatar
Penom Nom committed
412
413
414
415
416
417
418
419
420
421
422
    @staticmethod
    def get_directories_structure_and_content(ng6_username, data_folder, output_folder, prefixed_ids):
        from ng6.t3MySQLdb import t3MySQLdb
        src_directories = []
        dest_directories = []
        t3mysql = t3MySQLdb()
        
        user_id = None
        try : user_id = t3mysql.get_user_id(ng6_username)
        except : pass
        
423
        
Penom Nom's avatar
Penom Nom committed
424
425
426
427
428
429
430
        for prefixed_id in prefixed_ids.split(';') :
            vals = prefixed_id.split('_')
            prefix = vals[0]
            id = vals[1]
            if prefix == "data" or prefix == "run" :
                run = t3mysql.select_run_informations(id)
                source_dir = data_folder +'/'+ run['directory']
431
                project_name = Utils.get_project_dirname(run['project_id'],run['project_name'])
Romain Therville's avatar
Romain Therville committed
432
                
433
                #run_name = "Run_%s.%s" %( run['name'].replace(' ', '_').replace('/', '_'), id )
434
                run_name = Utils.get_run_dirname(id,run['name'])
Penom Nom's avatar
Penom Nom committed
435
436
                
                raw_data_dir = os.path.join( output_folder, project_name, run_name, "RawData"  )
437
                print (run, source_dir,project_name,run_name)
Penom Nom's avatar
Penom Nom committed
438
439
440
441
442
443
444
445
                if source_dir not in src_directories :
                    src_directories.append(source_dir)
                if raw_data_dir not in dest_directories :
                    dest_directories.append(raw_data_dir)
                
                if prefix == "run" :
                    for analyse_id, analyse_values in t3mysql.get_user_run_analysis(user_id, id, 'tx_nG6_analyze.name').items() :
                        analysis_dir = data_folder + '/' + analyse_values["directory"]
446
                        analysis_name = Utils.get_analyse_dirname(analyse_id, analyse_values['name'] )
Penom Nom's avatar
Penom Nom committed
447
                        dest_analysis_dir = os.path.join( output_folder, project_name, run_name, analysis_name  )
Romain Therville's avatar
Romain Therville committed
448
                        
Penom Nom's avatar
Penom Nom committed
449
450
451
452
453
454
455
456
457
458
459
460
                        if analysis_dir not in src_directories :
                            src_directories.append(analysis_dir)
                        if dest_analysis_dir not in dest_directories :
                            dest_directories.append(dest_analysis_dir)
                        
            elif prefix == "analyse" :
                analyse = t3mysql.select_analysis_informations(id)
                source_dir = data_folder +'/'+ analyse["directory"]
                
                if source_dir not in src_directories :
                    src_directories.append(source_dir)
                
461
                project_name = Utils.get_project_dirname(analyse['project_id'],analyse['project_name'])
Penom Nom's avatar
Penom Nom committed
462
                # it's a run analysis
463
464
465
466
                if analyse["run_id"]:                    
                    run_name = Utils.get_run_dirname(analyse["run_id"], analyse["run_name"])

                    analysis_name = Utils.get_analyse_dirname(id, analyse['name'] )
Penom Nom's avatar
Penom Nom committed
467
                    dest_analysis_dir = os.path.join( output_folder, project_name, run_name, analysis_name )
468
                    
Penom Nom's avatar
Penom Nom committed
469
470
471
472
                    if dest_analysis_dir not in dest_directories :
                        dest_directories.append(dest_analysis_dir)
                # it's a project analysis
                else :
473
                    analysis_name = "Project_"+ Utils.get_analyse_dirname(id, analyse['name'] ) 
Penom Nom's avatar
Penom Nom committed
474
475
476
477
478
479
480
481
482
483
484
485
486
487
                    dest_analysis_dir = os.path.join( output_folder, project_name, analysis_name )
                    if dest_analysis_dir not in dest_directories :
                        dest_directories.append(dest_analysis_dir)
        
        if len(src_directories) != len(dest_directories) :
            raise Exception("Error while retrieveing directory structure and content")
        
        sources, destinations = [], []
        
        for i, e in enumerate(src_directories):
            if os.path.isdir(e) :
                sources.append(e)
                destinations.append(dest_directories[i])
        return sources, destinations 
488
489
490
    
    @staticmethod    
    def rsync_getcmd( source, destination):
491
492
493
        if source == "" or not os.path.isdir(source) :
             return [ 0, "Source directory '" + source + "' doesn't exist, ignored."]
        
494
495
496
        if not source.endswith("/"):
            source+="/"
        cmd = ["rsync", "-avh", "--perms", "--times", "--remove-sent-files", source, destination]
497
        
498
        print("\n".join(cmd))
499
        
500
501
502
503
504
505
506
507
508
        retcode = call(cmd , shell=False)
        #Delete the old directory if empty
        if retcode >= 0 and os.path.isdir(source) and not os.listdir(source):
            try:
                os.rmdir(source)
            except Exception as err:
                raise Exception("Error while deleting " + source + "\n" + str(err) + "\n")
        return [ retcode, " ".join(cmd)]
    
509
510
511
512
513
514
515
516
517
    def get_purge_demand_directories(demand_ids):
        from ng6.t3MySQLdb import t3MySQLdb
        t3mysql = t3MySQLdb()
        return t3mysql.select_purge_demand_directories(demand_ids)
    
    def set_purge_demand_deleted(demand_ids):
        from ng6.t3MySQLdb import t3MySQLdb
        t3mysql = t3MySQLdb()
        return t3mysql.set_purge_demand_deleted(demand_ids)
Penom Nom's avatar
Penom Nom committed
518

519
    
Penom Nom's avatar
Penom Nom committed
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
class SSH(object): 
    def __init__(self, user, passwd, hostname, port=22):
        self.username = user
        self.password = passwd
        self.hostname = hostname
        self.port = port

    def run_cmd(self, c):
        (pid, f) = pty.fork()
        if pid == 0:
            os.execlp('ssh', 'ssh', '-p %d' % self.port, '-o StrictHostKeyChecking=no' ,
                      self.username + '@' + self.hostname, c)
        else:
            return (pid, f)     
    
    def _read(self, f):
Penom Nom's avatar
Penom Nom committed
536
        x = b''
Penom Nom's avatar
Penom Nom committed
537
538
        try:
            x = os.read(f, 1024)
Penom Nom's avatar
Penom Nom committed
539
        except Exception as e:
Penom Nom's avatar
Penom Nom committed
540
541
            # this always fails with io error
            pass
Penom Nom's avatar
Penom Nom committed
542
        return x.decode()
Penom Nom's avatar
Penom Nom committed
543
544
545
546
547
548
549

    def ssh_results(self, pid, f):
        output = ''
        got = self._read(f)         # check for authenticity of host request
        m = re.search( 'assword:', got)
        if m:
            # send passwd
Penom Nom's avatar
Penom Nom committed
550
            os.write(f, (self.password + '\n').encode() )
Penom Nom's avatar
Penom Nom committed
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
            # read two lines
            tmp = self._read(f)
            tmp += self._read(f)
            m = re.search('Permission denied', tmp)
            if m:
                raise Exception( 'Invalid password')
            # passwd was accepted
            got = tmp
        while got and len(got) > 0:
            output += got
            got = self._read(f)
        os.waitpid(pid, 0)
        os.close(f)
        return output

    def cmd(self, c):
        (pid, f) = self.run_cmd(c)
        return self.ssh_results(pid, f)


571