Running Sudo Command with paramiko

前端 未结 4 836
北荒
北荒 2020-11-30 08:25

I am trying to execute a sudo command on a remote machine using python-paramiko, when I execute the command, I bind it with 3 streams, and I use the input stream to pass the

4条回答
  •  遥遥无期
    2020-11-30 08:32

    I know this question is kind of old but I was wanting to use sudo and paramiko together, too. It took me a while to figure out this solution. It may not work for everyone but I figured it was worth adding.

    def ssh_handler(hostname, username=USER, password=PASS, command=CMD): 
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname,
                    username=username,
                    password=password) 
    
        stdin, stdout, stderr = ssh.exec_command(prepare_command(command))
        # stdin.write(password+'\n')  
    
        response = stdout.read()   
        ssh.close()
        print response
    
    
    def prepare_command(command):  
        if (not isinstance(command, basestring)): 
            command = ' ; '.join(command)  
        command = command.replace('"','\"') 
        command = 'sudo -s -- " '+command+' " \n'
        return command
    
    
    # kind of a dumb example but you get the point 
    mycmd = []; 
    mycmd.append('cd /dir/this/user/doesnt/have/access/to')
    mycmd.append('ls -las')
    mycmd.append('cat file_in_dir.txt')
    
    ssh_handler(server, command=mycmd)
    

提交回复
热议问题