Using sudo in Fabric

I’m using Xubuntu 12.04.03 32bit

If you haven’t seen my previous tutorial you should see it:
Fabric hello world

In this tutorial I’m using sudo to copy logs.

Create folder and fabfile.py.

$ mkdir sudofabric && cd sudofabric
$ nano fabfile.py

Create two methods: super and superfolder.

from fabric.api import  env, run, get, sudo

env.hosts=["[email protected]", "[email protected]",
                "[email protected]", "[email protected]"]

#env.password="password"
env.parallel=True

def super():
    sudo("cp /var/log/syslog $HOME")
    me = run("whoami")
    sudo("chown -R "+me+" /home/"+me)
    get("syslog")

def superfolder():
    sudo("cp -r /var/log/apt/ $HOME")
    me = run("whoami")
    sudo("chown -R "+me+" /home/"+me)
    get("apt")

Modify sudoers file. (WARNING: modifying wrong or giving rights to wrong person could compromise your computer)

$ sudo visudo

Because I don’t want to give password everytime running fabfile I give rights to all 4 user to run sudo without password. I added these lines to end of sudoers file

soivite01 ALL=(ALL) NOPASSWD: ALL
soivite02 ALL=(ALL) NOPASSWD: ALL
soivite03 ALL=(ALL) NOPASSWD: ALL
soivite04 ALL=(ALL) NOPASSWD: ALL

$ Run super command.

$ fab super

[[email protected]] Executing task 'super'
[[email protected]] sudo: cp /var/log/syslog $HOME
[[email protected]] run: whoami
[[email protected]] out: soivite01
[[email protected]] sudo: chown -R soivite01 /home/soivite01
[[email protected]] download: /home/xubuntu/fabric/[email protected]/syslog <- /home/soivite01/syslog
...

Run superfolder command.

$ fab superfolder

Your folder tree should look like this.

sudofabric/
├── fabfile.py
├── fabfile.pyc
├── [email protected]
│   ├── apt
│   │   ├── history.log
│   │   └── term.log
│   └── syslog
├── [email protected]
│   ├── apt
│   │   ├── history.log
│   │   └── term.log
│   └── syslog
├── [email protected]
│   ├── apt
│   │   ├── history.log
│   │   └── term.log
│   └── syslog
└── [email protected]
    ├── apt
    │   ├── history.log
    │   └── term.log
    └── syslog

Source:
Fabric tutorial 1 – Take command of your network

This post is part of course