fab [options] -- [shell command]
fab -H system1,system2,system3 -- uname -a
实例:
fab -H localhost -- uname -a
或者写ip
fab -H 192.168.241.100-- uname -a
输出:
[192.168.241.100] Executing task '<remainder>'
[192.168.241.100] run: uname -a
[192.168.241.100] out: Linux ubuntuDell 3.2.0-32-generic #51-Ubuntu SMP Wed Sep 26 21:33:09 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
Done.
Disconnecting from 192.168.241.100... done
2.文件的形式
文件名
默认fabfile.py,如果要修改为其他文件名,命令需要加入参数-f filename.py
from fabric.api import run,env
env.hosts = ['192.168.241.102']
env.user = 'yongyou'
env.password = 'yongyou'
def host_type():
run('uname -s')
保存文件
执行命令:fab host_type
输出:
[192.168.241.102] Executing task 'host_type'
[192.168.241.102] run: uname -s
[192.168.241.102] out: Linux
Done.
Disconnecting from 192.168.241.102... done.
连接不上服务器会提示:
[192.168.241.101] Executing task 'host_type'
[192.168.241.101] run: uname -s
Fatal error: Low level socket error connecting to host 192.168.241.101: No route to host
Aborting.
文件中如果把主机,用户名,密码三行去掉。执行fab host_type
的时候提示让输入主机信息,密码,(密码还不知道如何输入正确)
root@ubuntuDell:/home/wsl# fab host_type
No hosts found. Please specify (single) host string for connection: 192.168.241.100
[192.168.241.100] run: uname -s
[192.168.241.100] Login password:
[192.168.241.100] Login password:
[192.168.241.100] Login password:
[192.168.241.100] Login password:
[192.168.241.100] Login password:
或者执行fab -H 192.168.241.100 host_type
提示输入密码,和上述一样
可以用下面的命令,用户名和密码要正确,否则一直提示login password。密码输错了重新输入即可,用户名输入错了,一直提示login password,还没找到解决办法
fab -H 192.168.241.100 -u yongyou -p yongyou host_type
提示:
[192.168.241.100] Executing task 'host_type'
[192.168.241.100] run: uname -s
[192.168.241.100] out: Linux
Done.
Disconnecting from 192.168.241.100... done.
多台机器操作的情况:
fab -H 192.168.241.100,192.168.241.102 -u yongyou -p yongyou host_type
[192.168.241.100] Executing task 'host_type'
[192.168.241.100] run: uname -s
[192.168.241.100] out: Linux
[192.168.241.102] Executing task 'host_type'
[192.168.241.102] run: uname -s
[192.168.241.102] out: Linux
Done.
Disconnecting from 192.168.241.102... done.
Disconnecting from 192.168.241.100... done.
实例:
1.fab1.py
from fabric.api import run, env
env.hosts = ['host1', 'host2']
env.user = 'yongyou'
env.password = 'yongyou'
def taskA():
run('ls')
def taskB():
run('whoami')
执行:
fab -f fab1.py taskA taskB
在fab1.py 的taskB中加入下面一句话,两种形式,可以看到环境变量是如何应用的。
print("Executing on %s as %s" % (env.host, env.user))
print("Executing on %(host)s as %(user)s" % env)
可以使用的包:
from fabric.api import abort, cd, env, get, hide, hosts, local, prompt, put, require, roles, run, runs_once, settings, show, sudo, warn