Execute a command on Remote Machine in Python

后端 未结 4 1138
死守一世寂寞
死守一世寂寞 2020-12-02 10:53

I am writing a program in python on Ubuntu, to execute a command ls -l on RaspberryPi, connect with Network.

Can anybody guide me on how do I do that?

4条回答
  •  一个人的身影
    2020-12-02 11:19

    Paramiko module can be used to run multiple commands by invoking shell. Here I created class to invoke ssh shell

    class ShellHandler:

    def __init__(self, host, user, psw):
        logger.debug("Initialising instance of ShellHandler host:{0}".format(host))
        try:
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(host, username=user, password=psw, port=22)
            self.channel = self.ssh.invoke_shell()
        except:
            logger.error("Error Creating ssh connection to {0}".format(host))
            logger.error("Exiting ShellHandler")
            return
        self.psw=psw
        self.stdin = self.channel.makefile('wb')
        self.stdout = self.channel.makefile('r')
        self.host=host
        time.sleep(2)
    
        while not self.channel.recv_ready():
            time.sleep(2)
        self.initialprompt=""
        while self.channel.recv_ready():
    
            rl, wl, xl = select.select([ self.stdout.channel ], [ ], [ ], 0.0)
            if len(rl) > 0:
                tmp = self.stdout.channel.recv(24)
                self.initialprompt=self.initialprompt+str(tmp.decode())
    
    
    
    def __del__(self):
        self.ssh.close()
        logger.info("closed connection to {0}".format(self.host))
    
    def execute(self, cmd):
        cmd = cmd.strip('\n')
        self.stdin.write(cmd + '\n')
        #self.stdin.write(self.psw +'\n')
        self.stdin.flush()
        time.sleep(1)
        while not self.stdout.channel.recv_ready():
            time.sleep(2)
            logger.debug("Waiting for recv_ready")
    
        output=""
        while self.channel.recv_ready():
            rl, wl, xl = select.select([ self.stdout.channel ], [ ], [ ], 0.0)
            if len(rl) > 0:
                tmp = self.stdout.channel.recv(24)
                output=output+str(tmp.decode())
        return output
    

    If creating different shell each time does not matter to you then you can use method as below.

    def run_cmd(self,cmd):
        try:
            cmd=cmd+'\n'
            #self.ssh.settimeout(60)
            stdin,stdout,stderr=self.ssh.exec_command(cmd)
            while not stdout.channel.eof_received:
               time.sleep(3)
               logger.debug("Waiting for eof_received")
            out=""
            while stdout.channel.recv_ready():
                err=stderr.read()
                if err:
                    print("Error: ",my_hostname, str(err))
                    return False 
    
                out=out+stdout.read()
            if out:
                   return out 
    
        except:
            error=sys.exc_info()
            logger.error(error)
            return False 
    

提交回复
热议问题