1*4882a593Smuzhiyun# 2*4882a593Smuzhiyun# Copyright (C) 2013 Intel Corporation 3*4882a593Smuzhiyun# 4*4882a593Smuzhiyun# SPDX-License-Identifier: MIT 5*4882a593Smuzhiyun# 6*4882a593Smuzhiyun 7*4882a593Smuzhiyun# Provides a class for setting up ssh connections, 8*4882a593Smuzhiyun# running commands and copying files to/from a target. 9*4882a593Smuzhiyun# It's used by testimage.bbclass and tests in lib/oeqa/runtime. 10*4882a593Smuzhiyun 11*4882a593Smuzhiyunimport subprocess 12*4882a593Smuzhiyunimport time 13*4882a593Smuzhiyunimport os 14*4882a593Smuzhiyunimport select 15*4882a593Smuzhiyun 16*4882a593Smuzhiyun 17*4882a593Smuzhiyunclass SSHProcess(object): 18*4882a593Smuzhiyun def __init__(self, **options): 19*4882a593Smuzhiyun 20*4882a593Smuzhiyun self.defaultopts = { 21*4882a593Smuzhiyun "stdout": subprocess.PIPE, 22*4882a593Smuzhiyun "stderr": subprocess.STDOUT, 23*4882a593Smuzhiyun "stdin": None, 24*4882a593Smuzhiyun "shell": False, 25*4882a593Smuzhiyun "bufsize": -1, 26*4882a593Smuzhiyun "start_new_session": True, 27*4882a593Smuzhiyun } 28*4882a593Smuzhiyun self.options = dict(self.defaultopts) 29*4882a593Smuzhiyun self.options.update(options) 30*4882a593Smuzhiyun self.status = None 31*4882a593Smuzhiyun self.output = None 32*4882a593Smuzhiyun self.process = None 33*4882a593Smuzhiyun self.starttime = None 34*4882a593Smuzhiyun self.logfile = None 35*4882a593Smuzhiyun 36*4882a593Smuzhiyun # Unset DISPLAY which means we won't trigger SSH_ASKPASS 37*4882a593Smuzhiyun env = os.environ.copy() 38*4882a593Smuzhiyun if "DISPLAY" in env: 39*4882a593Smuzhiyun del env['DISPLAY'] 40*4882a593Smuzhiyun self.options['env'] = env 41*4882a593Smuzhiyun 42*4882a593Smuzhiyun def log(self, msg): 43*4882a593Smuzhiyun if self.logfile: 44*4882a593Smuzhiyun with open(self.logfile, "a") as f: 45*4882a593Smuzhiyun f.write("%s" % msg) 46*4882a593Smuzhiyun 47*4882a593Smuzhiyun def _run(self, command, timeout=None, logfile=None): 48*4882a593Smuzhiyun self.logfile = logfile 49*4882a593Smuzhiyun self.starttime = time.time() 50*4882a593Smuzhiyun output = '' 51*4882a593Smuzhiyun self.process = subprocess.Popen(command, **self.options) 52*4882a593Smuzhiyun if timeout: 53*4882a593Smuzhiyun endtime = self.starttime + timeout 54*4882a593Smuzhiyun eof = False 55*4882a593Smuzhiyun while time.time() < endtime and not eof: 56*4882a593Smuzhiyun try: 57*4882a593Smuzhiyun if select.select([self.process.stdout], [], [], 5)[0] != []: 58*4882a593Smuzhiyun data = os.read(self.process.stdout.fileno(), 1024) 59*4882a593Smuzhiyun if not data: 60*4882a593Smuzhiyun self.process.stdout.close() 61*4882a593Smuzhiyun eof = True 62*4882a593Smuzhiyun else: 63*4882a593Smuzhiyun data = data.decode("utf-8") 64*4882a593Smuzhiyun output += data 65*4882a593Smuzhiyun self.log(data) 66*4882a593Smuzhiyun endtime = time.time() + timeout 67*4882a593Smuzhiyun except InterruptedError: 68*4882a593Smuzhiyun continue 69*4882a593Smuzhiyun 70*4882a593Smuzhiyun # process hasn't returned yet 71*4882a593Smuzhiyun if not eof: 72*4882a593Smuzhiyun self.process.terminate() 73*4882a593Smuzhiyun time.sleep(5) 74*4882a593Smuzhiyun try: 75*4882a593Smuzhiyun self.process.kill() 76*4882a593Smuzhiyun except OSError: 77*4882a593Smuzhiyun pass 78*4882a593Smuzhiyun lastline = "\nProcess killed - no output for %d seconds. Total running time: %d seconds." % (timeout, time.time() - self.starttime) 79*4882a593Smuzhiyun self.log(lastline) 80*4882a593Smuzhiyun output += lastline 81*4882a593Smuzhiyun else: 82*4882a593Smuzhiyun output = self.process.communicate()[0] 83*4882a593Smuzhiyun self.log(output.rstrip()) 84*4882a593Smuzhiyun 85*4882a593Smuzhiyun self.status = self.process.wait() 86*4882a593Smuzhiyun self.output = output.rstrip() 87*4882a593Smuzhiyun 88*4882a593Smuzhiyun def run(self, command, timeout=None, logfile=None): 89*4882a593Smuzhiyun try: 90*4882a593Smuzhiyun self._run(command, timeout, logfile) 91*4882a593Smuzhiyun except: 92*4882a593Smuzhiyun # Need to guard against a SystemExit or other exception occuring whilst running 93*4882a593Smuzhiyun # and ensure we don't leave a process behind. 94*4882a593Smuzhiyun if self.process.poll() is None: 95*4882a593Smuzhiyun self.process.kill() 96*4882a593Smuzhiyun self.status = self.process.wait() 97*4882a593Smuzhiyun raise 98*4882a593Smuzhiyun return (self.status, self.output) 99*4882a593Smuzhiyun 100*4882a593Smuzhiyunclass SSHControl(object): 101*4882a593Smuzhiyun def __init__(self, ip, logfile=None, timeout=300, user='root', port=None): 102*4882a593Smuzhiyun self.ip = ip 103*4882a593Smuzhiyun self.defaulttimeout = timeout 104*4882a593Smuzhiyun self.ignore_status = True 105*4882a593Smuzhiyun self.logfile = logfile 106*4882a593Smuzhiyun self.user = user 107*4882a593Smuzhiyun self.ssh_options = [ 108*4882a593Smuzhiyun '-o', 'UserKnownHostsFile=/dev/null', 109*4882a593Smuzhiyun '-o', 'StrictHostKeyChecking=no', 110*4882a593Smuzhiyun '-o', 'LogLevel=ERROR' 111*4882a593Smuzhiyun ] 112*4882a593Smuzhiyun self.ssh = ['ssh', '-l', self.user ] + self.ssh_options 113*4882a593Smuzhiyun self.scp = ['scp'] + self.ssh_options 114*4882a593Smuzhiyun if port: 115*4882a593Smuzhiyun self.ssh = self.ssh + [ '-p', port ] 116*4882a593Smuzhiyun self.scp = self.scp + [ '-P', port ] 117*4882a593Smuzhiyun 118*4882a593Smuzhiyun def log(self, msg): 119*4882a593Smuzhiyun if self.logfile: 120*4882a593Smuzhiyun with open(self.logfile, "a") as f: 121*4882a593Smuzhiyun f.write("%s\n" % msg) 122*4882a593Smuzhiyun 123*4882a593Smuzhiyun def _internal_run(self, command, timeout=None, ignore_status = True): 124*4882a593Smuzhiyun self.log("[Running]$ %s" % " ".join(command)) 125*4882a593Smuzhiyun 126*4882a593Smuzhiyun proc = SSHProcess() 127*4882a593Smuzhiyun status, output = proc.run(command, timeout, logfile=self.logfile) 128*4882a593Smuzhiyun 129*4882a593Smuzhiyun self.log("[Command returned '%d' after %.2f seconds]" % (status, time.time() - proc.starttime)) 130*4882a593Smuzhiyun 131*4882a593Smuzhiyun if status and not ignore_status: 132*4882a593Smuzhiyun raise AssertionError("Command '%s' returned non-zero exit status %d:\n%s" % (command, status, output)) 133*4882a593Smuzhiyun 134*4882a593Smuzhiyun return (status, output) 135*4882a593Smuzhiyun 136*4882a593Smuzhiyun def run(self, command, timeout=None): 137*4882a593Smuzhiyun """ 138*4882a593Smuzhiyun command - ssh command to run 139*4882a593Smuzhiyun timeout=<val> - kill command if there is no output after <val> seconds 140*4882a593Smuzhiyun timeout=None - kill command if there is no output after a default value seconds 141*4882a593Smuzhiyun timeout=0 - no timeout, let command run until it returns 142*4882a593Smuzhiyun """ 143*4882a593Smuzhiyun 144*4882a593Smuzhiyun command = self.ssh + [self.ip, 'export PATH=/usr/sbin:/sbin:/usr/bin:/bin; ' + command] 145*4882a593Smuzhiyun 146*4882a593Smuzhiyun if timeout is None: 147*4882a593Smuzhiyun return self._internal_run(command, self.defaulttimeout, self.ignore_status) 148*4882a593Smuzhiyun if timeout == 0: 149*4882a593Smuzhiyun return self._internal_run(command, None, self.ignore_status) 150*4882a593Smuzhiyun return self._internal_run(command, timeout, self.ignore_status) 151*4882a593Smuzhiyun 152*4882a593Smuzhiyun def copy_to(self, localpath, remotepath): 153*4882a593Smuzhiyun if os.path.islink(localpath): 154*4882a593Smuzhiyun localpath = os.path.dirname(localpath) + "/" + os.readlink(localpath) 155*4882a593Smuzhiyun command = self.scp + [localpath, '%s@%s:%s' % (self.user, self.ip, remotepath)] 156*4882a593Smuzhiyun return self._internal_run(command, ignore_status=False) 157*4882a593Smuzhiyun 158*4882a593Smuzhiyun def copy_from(self, remotepath, localpath): 159*4882a593Smuzhiyun command = self.scp + ['%s@%s:%s' % (self.user, self.ip, remotepath), localpath] 160*4882a593Smuzhiyun return self._internal_run(command, ignore_status=False) 161*4882a593Smuzhiyun 162*4882a593Smuzhiyun def copy_dir_to(self, localpath, remotepath): 163*4882a593Smuzhiyun """ 164*4882a593Smuzhiyun Copy recursively localpath directory to remotepath in target. 165*4882a593Smuzhiyun """ 166*4882a593Smuzhiyun 167*4882a593Smuzhiyun for root, dirs, files in os.walk(localpath): 168*4882a593Smuzhiyun # Create directories in the target as needed 169*4882a593Smuzhiyun for d in dirs: 170*4882a593Smuzhiyun tmp_dir = os.path.join(root, d).replace(localpath, "") 171*4882a593Smuzhiyun new_dir = os.path.join(remotepath, tmp_dir.lstrip("/")) 172*4882a593Smuzhiyun cmd = "mkdir -p %s" % new_dir 173*4882a593Smuzhiyun self.run(cmd) 174*4882a593Smuzhiyun 175*4882a593Smuzhiyun # Copy files into the target 176*4882a593Smuzhiyun for f in files: 177*4882a593Smuzhiyun tmp_file = os.path.join(root, f).replace(localpath, "") 178*4882a593Smuzhiyun dst_file = os.path.join(remotepath, tmp_file.lstrip("/")) 179*4882a593Smuzhiyun src_file = os.path.join(root, f) 180*4882a593Smuzhiyun self.copy_to(src_file, dst_file) 181*4882a593Smuzhiyun 182*4882a593Smuzhiyun 183*4882a593Smuzhiyun def delete_files(self, remotepath, files): 184*4882a593Smuzhiyun """ 185*4882a593Smuzhiyun Delete files in target's remote path. 186*4882a593Smuzhiyun """ 187*4882a593Smuzhiyun 188*4882a593Smuzhiyun cmd = "rm" 189*4882a593Smuzhiyun if not isinstance(files, list): 190*4882a593Smuzhiyun files = [files] 191*4882a593Smuzhiyun 192*4882a593Smuzhiyun for f in files: 193*4882a593Smuzhiyun cmd = "%s %s" % (cmd, os.path.join(remotepath, f)) 194*4882a593Smuzhiyun 195*4882a593Smuzhiyun self.run(cmd) 196*4882a593Smuzhiyun 197*4882a593Smuzhiyun 198*4882a593Smuzhiyun def delete_dir(self, remotepath): 199*4882a593Smuzhiyun """ 200*4882a593Smuzhiyun Delete remotepath directory in target. 201*4882a593Smuzhiyun """ 202*4882a593Smuzhiyun 203*4882a593Smuzhiyun cmd = "rmdir %s" % remotepath 204*4882a593Smuzhiyun self.run(cmd) 205*4882a593Smuzhiyun 206*4882a593Smuzhiyun 207*4882a593Smuzhiyun def delete_dir_structure(self, localpath, remotepath): 208*4882a593Smuzhiyun """ 209*4882a593Smuzhiyun Delete recursively localpath structure directory in target's remotepath. 210*4882a593Smuzhiyun 211*4882a593Smuzhiyun This function is very usefult to delete a package that is installed in 212*4882a593Smuzhiyun the DUT and the host running the test has such package extracted in tmp 213*4882a593Smuzhiyun directory. 214*4882a593Smuzhiyun 215*4882a593Smuzhiyun Example: 216*4882a593Smuzhiyun pwd: /home/user/tmp 217*4882a593Smuzhiyun tree: . 218*4882a593Smuzhiyun └── work 219*4882a593Smuzhiyun ├── dir1 220*4882a593Smuzhiyun │ └── file1 221*4882a593Smuzhiyun └── dir2 222*4882a593Smuzhiyun 223*4882a593Smuzhiyun localpath = "/home/user/tmp" and remotepath = "/home/user" 224*4882a593Smuzhiyun 225*4882a593Smuzhiyun With the above variables this function will try to delete the 226*4882a593Smuzhiyun directory in the DUT in this order: 227*4882a593Smuzhiyun /home/user/work/dir1/file1 228*4882a593Smuzhiyun /home/user/work/dir1 (if dir is empty) 229*4882a593Smuzhiyun /home/user/work/dir2 (if dir is empty) 230*4882a593Smuzhiyun /home/user/work (if dir is empty) 231*4882a593Smuzhiyun """ 232*4882a593Smuzhiyun 233*4882a593Smuzhiyun for root, dirs, files in os.walk(localpath, topdown=False): 234*4882a593Smuzhiyun # Delete files first 235*4882a593Smuzhiyun tmpdir = os.path.join(root).replace(localpath, "") 236*4882a593Smuzhiyun remotedir = os.path.join(remotepath, tmpdir.lstrip("/")) 237*4882a593Smuzhiyun self.delete_files(remotedir, files) 238*4882a593Smuzhiyun 239*4882a593Smuzhiyun # Remove dirs if empty 240*4882a593Smuzhiyun for d in dirs: 241*4882a593Smuzhiyun tmpdir = os.path.join(root, d).replace(localpath, "") 242*4882a593Smuzhiyun remotedir = os.path.join(remotepath, tmpdir.lstrip("/")) 243*4882a593Smuzhiyun self.delete_dir(remotepath) 244