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 from fabric import Connectionhost='192.168.10.102' user=('root' ) con=Connection(host=host,user=user,connect_kwargs={'password' :'1' }) result=con.run('df -Th' ,hide=True ) print (result.stdout.strip())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 import os.pathfrom fabric import Connectionhost='192.168.10.114' user='root' con=Connection(host=host,user=user,connect_kwargs={'password' :'1' }) con.put('D:/config' ,'/tmp/config' ) 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()
使用with自动关闭连接
1 2 3 4 5 6 from fabric import Connectionwith Connection(host='192.168.10.114' ,user='root' ,connect_kwargs={'password' :'1' }) as conn: result = conn.sudo('uptime' ,hide=True ) print (result.stdout)