大家好,我是testerzhang, 好久没更新文章了,终于有时间静下心来写一下。今天跟大家分享利用fabric来批量操作服务器。
$ python3 -V
Python 3.9.6
$ pip3 list|grep fab
fabric 2.7.0
•python3 版本可以更高些,这里用了现成的环境3.9x。•fabirc使用了2.x版本
•在当前目录创建一个fabfile.py
文件,内容如下:
$ cat fabfile.py
from fabric import task
@task
def hello(null):
print("hello world")
执行一下:
$ fab hello
hello world
$ cat fabfile.py
from fabric import task
from fabric.connection import Connection
@task
def remoteTest(c):
host = "127.0.0.1"
port = 22222
user = "testerzhang"
password = "实际密码"
conn = Connection(host, port=port, user=user, connect_kwargs={"password": password})
conn.run("/sbin/ifconfig eth0")
执行
$ fab remoteTest
$ cat fabfile.py
from fabric import task
from fabric.connection import Connection
@task
def remoteTest2(c):
host = "127.0.0.1"
port = 22222
user = "testerzhang"
key_filename = "/home/testerzhang/.ssh/config"
conn = Connection(host, port=port, user=user, connect_kwargs={"key_filename": key_filename})
conn.run("/sbin/ifconfig eth0")
$ cat ~/.fabric.yaml
ssh_config_path: /home/testerzhang/.ssh/config
当然还有其他配置项,这里就不列举了,有兴趣再去官方网站看看。
$ cat fabfile.py
from fabric import task
from fabric.connection import Connection
@task
def remoteTest3(c):
host = "127.0.0.1"
port = 22222
user = "testerzhang"
conn = Connection(host, port=port, user=user )
conn.run("/sbin/ifconfig eth0")
如果你在ssh配置文件里已经配置了别名host,那么更简单
$ cat fabfile.py
from fabric import task
from fabric.connection import Connection
@task
def remoteTest3(c):
host_alias = "testerzhanghostalias"
conn = Connection(host_alias)
conn.run("/sbin/ifconfig eth0")
下面举例:登录服务器testerzhang账号,然后切换到music用户,输入密码登录成功后执行id命令
from fabric import task
from fabric.connection import Connection
from invoke import Responder
def get_su_do_pass(user_pass):
sudopass = Responder(
pattern=r'assword:',
response=f'{user_pass}\n',
)
return sudopass
@task
def remoteTest4(c):
host = "127.0.0.1"
port = 22022
user = "testerzhang"
switch_user = "music"
switch_pass = "musicpass"
switch_cmd = "id"
with Connection(host, port=port, user=user) as c:
try:
cmd = f'''export LANG=C; su - {switch_user} -c "{switch_cmd}" '''
result = c.run(cmd, hide=True, pty=True,watchers=[get_su_do_pass(switch_pass)])
stdout = result.stdout
stderr = result.stderr
if len(stderr) == 0:
stdout = stdout.replace("Password:", "")
print(f"[{host}]执行成功:{stdout}")
else:
print(f"[{host}]执行失败:{stderr}")
except UnexpectedExit as e :
print(f"执行异常:{e.result}")
1.配置fabric.yml文件,提前配置好主机。2.利用ssh的配置文件,提前配置好主机。
今天就讲到这里,至于怎么上传文件,下载文件,可以脚本执行scp命令触发。
自己组建了一个新的交流群,需要进群交流,可以扫描下方加群二维码,也可以在公众号后台回复【加技术群】即可收到相应说明。
喜欢的话可以点击"收藏"进行稍后阅读,可以点击"在看"支持下,也可以分享下此文章给你的其他朋友。
欢迎关注我的公众号“testerzhang”,原创技术文章第一时间推送。
不错,赏个鸡腿!
微信扫一扫
关注该公众号