Akemi

Python fabric模块案例—更方便使用ssh

2024/11/08

fabric是一个更方便的使用ssh的模块,他集成了很多paramiko模块的内容

安装fabric库

pip3 install fabric

参数说明

command——要执行的命令 字符串
hide ——True,隐藏输出,相当于安静模式
warn ——True,非0输出也不会报错,使用非关键操作检查
pty—— True,使用伪终端执行命令

Connection模块执行远程命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#coding=utf-8
from fabric import Connection

host='192.168.10.102'
user=('root')

# 连接到远程服务器
con=Connection(host=host,user=user,connect_kwargs={'password':'1'})

# 执行命令,返回的结果给result
result=con.run('df -Th',hide=True)
print(result.stdout.strip())

# 使用sudo执行命令
result=con.sudo('free -h',password='1',hide=True)
print(result.stdout.strip())

远程上传下载文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#coding=utf-8
import os.path

from fabric import Connection
host='192.168.10.114'
user='root'

con=Connection(host=host,user=user,connect_kwargs={'password':'1'})

# 使用put方法,远程上传
con.put('D:/config','/tmp/config')
# 使用get方法,远程下载
con.get('/root/anaconda-ks.cfg','D:/anaconda-ks.cfg')

# 检查文件是否存在
con.run('[ -f /tmp/config ] && echo "file exists" ',warn=True)
if os.path.exists('D:/anaconda-ks.cfg'):
print("文件下载成功")

con.close()
# file exists
# 文件下载成功

使用with自动关闭连接

1
2
3
4
5
6
#coding=utf-8
from fabric import Connection

with Connection(host='192.168.10.114',user='root',connect_kwargs={'password':'1'}) as conn:
result = conn.sudo('uptime',hide=True)
print(result.stdout)
CATALOG