Skip to content

Ssh tool

SSH-TOOLS

#!/usr/bin/python

# This is used for ssh utility of devcies which do not need password to login...

import subprocess
import os

class target():

    def __init__(self, ip, user, password=None):
        self.ip = ip
        self.user = user

    def send_cmd(self, cmd):
        try:
            ssh_cmd=['ssh','-o','strictHostKeyChecking=no', f'{self.user}@{self.ip}',f'sh -lc "{cmd}"']
            with subprocess.Popen(ssh_cmd,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8') as proc:
                for line in proc.stdout:
                    print(line)
        except Exception as exp:
            print('fail to send cmd')
            raise exp

    def put(self, local_path, target_path):
        try:
            scp_cmd=['scp', '-o', 'strictHostKeyChecking=no']
            if os.path.isdir(local_path):
                scp_cmd.append('-r')
            elif os.path.isfile(local_path):
                pass
            else:
                raise FileNotFoundError(local_path)
            scp_cmd += [f'{local_path}',f'{self.user}@{self.ip}:{target_path}']
            with subprocess.Popen(scp_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8') as proc:
                for line in proc.stdout:
                    print(line)
        except Exception as exp:
            print('fail to put file to target')
            raise exp

    def get(self, local_path, target_path):
        try:
            scp_cmd=['scp', '-o', 'strictHostKeyChecking=no']
            if os.path.isdir(local_path):
                scp_cmd.append('-r')
            else:
                raise FileNotFoundError(local_path)
            scp_cmd += [f'{self.user}@{self.ip}:{target_path}',f'{local_path}']
            with subprocess.Popen(scp_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8') as proc:
                for line in proc.stdout:
                    print(line)
        except Exception as exp:
            print('fail to get file from target')
            raise exp
if __name__ == '__main__':
    rpi=target('192.168.50.129', 'ubuntu', 'ubuntu')
    fio_cmd="fio ~/example.fio --eta=always"
    rpi.send_cmd(fio_cmd)
    rpi.put('./test.py', '/tmp/')
    rpi.put('./src/', '/tmp/')
    rpi.get('./tmp/', '~/note_server/mkdocs.yaml')
    rpi.get('./tmp/', '~/note_server/docs')